Search code examples
djangodjango-class-based-viewsdjango-permissions

Restrict access to a part of a template to users that is part of a group using Class based views. Django 2.0


I want to restrict users in certain groups from accessing parts of the HTML template. I have a class based view that looks like this:

Views.py

class PostListView(ListView):
    model = BlogPost
    paginate_by = 10
    template_name = 'main/mysite.html'

With function based views I can restrict access on a template based on someones group using request.user.groups.filter(name='GROUP_NAME').exists() from In Django, how do I check if a user is in a certain group?

I tried changing my view.py and HTML template like this:

views.py

class PostListView(ListView):
    model = BlogPost
    paginate_by = 10
    template_name = 'main/mysite.html'

    def dispatch(self, request):
        in_group =  request.user.groups.filter(name='GROUP_NAME').exists()
        return in_group

HTML TEMPLATE

....
{% if in_group %}
some code here shows up if user belong to group
{% endif %}
....

This will give me the correct display when the user is not a member of the group, but when they are a member of the correct group I get an attribution error:

Exception Type: AttributeError at /mysite
Exception Value: 'bool' object has no attribute 'get'

Solution

  • The way to get a context variable into your template when using a class-based view is to override the get_context_data() method:

    class PostListView(ListView):
        model = BlogPost
        paginate_by = 10
        template_name = 'main/mysite.html'
    
        def get_context_data(self, **kwargs):
            context = super().get_context_data(**kwargs)
            context['in_group'] =  self.request.user.groups.filter(name='GROUP_NAME').exists()
            return context
    

    See the Django docs for more on get_context_data().