My context variables don't show in templates

17 views
Skip to first unread message

Mohamed Turki

unread,
May 19, 2012, 6:29:15 PM5/19/12
to django...@googlegroups.com
Hi,

I have a view called home that searches for a user in my UserProfile model and returns the username. I add this
username to the context variable and try to show it in the template. Pretty straightforward and simple, right? 
Well, here is my code first :

def home(request):
    var = ""
    n = None
    if request.method == u'GET':
        GET = request.GET
        if GET.has_key(u'name'):
            n = GET[u'name']
            try:
                user = UserProfile.objects.get(facebookId = n)
                user.is_active = True
                user.last_login = datetime.now()
                var = user.facebookId
                user.save()
                
                print var 
                
                
                #on log out
                if GET.has_key(u'logout'):
                    print 'im logging out!'
                    user = UserProfile.objects.get(facebookId = n)
                    user.is_active = False
                    user.last_login = datetime.now()
                    user.save()
                    
                    
                    
                    
            except:
                user = UserProfile(facebookId=n,playedHours=0, is_active=True)
                user.save()
                
        
    print var          
    context  = {'nom':var}
    return render_to_response('home.html',context,context_instance=RequestContext(request))
    
    
and in my template I have something as simple as :

{{ nom }}

However, when I replace var with a "bla bla bla" for example, it shows on my template, but when I pass a variable name to the 
context, it doesn't show ! I also can see the var value on my console (notice i'm using print twice or thrice in the code)

am I doing anything wrong here?

Thanks !












bruno desthuilliers

unread,
May 21, 2012, 8:37:35 AM5/21/12
to Django users
On May 20, 12:29 am, Mohamed Turki <turki...@gmail.com> wrote:
>
> def home(request):
>     var = ""
>     n = None

Better to use readable names.

>     if request.method == u'GET':
>         GET = request.GET
>         if GET.has_key(u'name'):
>             n = GET[u'name']
>             try:
>                 user = UserProfile.objects.get(facebookId = n)

In most django code, "user" will refer to a
django.contrib.auth.models.User instance. "profile" might be a better
name here (law of the least surprise).

>                 user.is_active = True
>                 user.last_login = datetime.now()
>                 var = user.facebookId

so "var" == "n" == "user.facebookId". Uhuh... Using three different
names for the same object in the same scope is possibly not a great
idea when it comes to readability.

>                 user.save()
>
>                 print var
>
>                 #on log out
>                 if GET.has_key(u'logout'):
>                     print 'im logging out!'
>                     user = UserProfile.objects.get(facebookId = n)
>                     user.is_active = False
>                     user.last_login = datetime.now()
>                     user.save()
>
>             except:

_never ever_ use a bare except clause, unless it's followed by a
"raise" statement. The actual exception might be very different than
what you assume it is (for the record, sys.exit() raise a SysExit
exception...)



>                 user = UserProfile(facebookId=n,playedHours=0,
> is_active=True)
>                 user.save()

Ok, so what if

1/ request.method != "GET"
2/ "name" not in request.GET
3/ any expected or unexpected exception sent you in the exception
handler ?

>     print var
>     context  = {'nom':var}

FWIW, Django's template system is smart enough to handle attribute
lookup. In practice you'd be better to populate your context with your
UserProfile instance...

>     return
> render_to_response('home.html',context,context_instance=RequestContext(request))
>
> and in my template I have something as simple as :
>
> {{ nom }}
>
> However, when I replace *var* with a "bla bla bla" for example, it shows on
> my template, but when I pass a variable name

What do you mean by "variable name" ???

> to the
> context, it doesn't show ! I also can see the *var* value on my console
> (notice i'm using print twice or thrice in the code)

Indeed - but possibly not in the most effective way. You'd have more
infos adding print statements in each and every branch giving clear
indications about what part of the code you're in ATM. A mere "print
var" will only output an empty line if var == "", so you can easily
miss it.


>
> am I doing anything wrong here?

Well, quite a few things yes ;)

... but if your last print statement shows the expected value, then
there's no reason (at the python / django level) it shouldn't show up
in your template.

To make sure your context is what you expect it to be, add a

print "context : %s" % context

line just before the return statement.

Reply all
Reply to author
Forward
0 new messages