Limiting access to some parts of the website

Hello every body. I am new to Django and I am trying to make a website.

I want to limit the access for registered users to some pages, i.e in the website there some parts you can’t access unless you satisfy some conditions (like points you have from solving exercises).

I am using CBV. I tried to change the template_name as follows:

    class MyView(DetailView):
       #...
       def __init__(self, **kwargs):
		if condition:
			self.template_name = 'someTemplate.html'
		else:
			self.template_name = 'otherTemplate.html'
		return super(MyView,self).__init__(**kwargs)

This method works, but I have to repeat this with each view.
My question is: Is there a better way to do that?
I tried to make a decorator, but I don’t know how to change template_name from the decorator.

I have another question related to this. If want a user to not see a hole section section/, and this section has other subsections (section/sub1, section/sub2, …), do I need to make restriction on each subsection?

Thank you in advance.

See the docs on the PermissionRequiredMixin along with the has_permission method.

What we have done is create a PermissionRequiredMixin subclass with a custom has_permission method. We then apply that mixin to our view classes that need to be protected.

If you’re not familiar with Python’s Method Resolution Order (MRO) and mixin classes, now’s a good time to add that to your reading list.

1 Like