[Django]-How to restrict access to pages based on user type in Django

3πŸ‘

βœ…

One solution could be to change the base template name depending on the user type:

@render_to('some_template.html')
def some_view(request):
    base_template = 'base_%s.html' % request.user.profile.type
    # …
    return {
        'base_template': base_template,
    }

And in your template :

{% extends base_template %}
{% block some-block %}
…
{% endblock %}

If you need to do this on every view, you could use a middleware to set this value.

πŸ‘€Thibault J

7πŸ‘

To restrict access, use the user passes test decorator:

from django.contrib.auth.decorators import user_passes_test

male_only = lamda u: u.type == 'M'
female_only = lamda u: u.type == 'F'


@user_passes_test(male_only)
def myfunc(request):
   pass

@user_passes_test(female_only)
def myotherfunc(request):
   pass
πŸ‘€Burhan Khalid

0πŸ‘

To add extra data to User see

Storing additional information about users

Then add the profile to your context and you can use {{profile}} variable in your template

{% if profile.type == "F" %}
    blah, blah
{% else %}
    blah, blah
{% endif %}
πŸ‘€pvilas

0πŸ‘

Depending on what you want to do, if you need to use very different html for different genders, you can try this approach:

def gender_filter(func):
    def _view(request,*args,**kwargs):
        res=func(request,*args,**kwargs)
        if request.user.get_profile().type=='F':
            res.template_name='template_f.html'
            res.context_data['gender']='female'
        elif request.user.get_profile().type=='M':
            res.template_name='template_m.html'
            res.context_data['gender']='male'
        return res.render()
    return _view

@gender_filter
def my_view(request):
    t=TemplateResponse(request,'template_f.html',{...})
    return t

So instead of returning Http resonpse in views, you can make them return TemplateResponse objects and use decorators to change templates, add in general context, and them convert them to HttpResponse.

Or something like a permission check:

def gender_only(gender):
    def _dec(func):
        def _view(request,*args,**kwargs):
            if request.user.get_profile().type==gender
                return func.render(request,*args,**kwargs)
            else:
                raise Exception("You do not have the right gender")
        return _view
    return _dec

@gender_only('F')
def my_view(request):
    ...
    return render_to_response('template.html',{...},context_instance=RequestContext(request))
πŸ‘€Xun Yang

Leave a comment