Monday, July 23, 2012

Re: Django TypeError

On Tuesday, July 17, 2012 8:00:39 AM UTC+2, sandy wrote:
I want to have different views for my application for different types
of users. For this I have this code for my views.py file :

def index1(request):
        u = User.objects.all()

This has been solved.
 
        if u.is_staff ==1 and u.is_active == 1 and u.is_superuser == 1:


User.is_staff, User.is_active and User.is_superuser already have a boolean value, so you don't need to test against 1 (or True etc).

        if u.is_staff  and u.is_active and u.is_superuser :


 
                return render_to_response('tcc11_12/index1.html',
context_instance=RequestContext(request))
        elif u.is_staff == 1 and u.is_active == 1 and u.is_superuser == 0:


You only have one different predicate here, so you could factor your tests:


     if u.is_staff  and u.is_active:
         if u.is_superuser :
             return render_to_response('tcc11_12/index1.html', context_instance=RequestContext(request))           
         else:
             return render_to_response('tcc11_12/index2.html', context_instance=RequestContext(request))
     else:
         return render_to_response('index3.html',context_instance=RequestContext(request))


Note that if only the template change, you could avoid multiple returns too:
    
     template = 'index3.html' # default
     if u.is_staff  and u.is_active:
         template = 'tcc11_12/index1.html' if u.is_superuser else  'tcc11_12/index2.html'
    
     return render_to_response(template,context_instance=RequestContext(request))


Also, if you're using request.user as the user *and the default authentication backend and auth form*, only "active" users should be able to log in, so your test on 'is_active' _may_ (or not !) be just useless:

https://docs.djangoproject.com/en/1.3/topics/auth/#django.contrib.auth.models.User.is_active

HTH

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To view this discussion on the web visit https://groups.google.com/d/msg/django-users/-/r11xbhdW5fAJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment