Search code examples
djangopython-3.xpython-3.7django-generic-viewsdjango-2.2

Django generic view, check if request is in the same group as creator


Im searching for a way to check user groups when request User is in the same group as the Creator then access and when not then access declined.

The reason behind this is that not every Staff Member may edit all contributions. Only if the staff member is in the same group as the author, then the staff member may edit the article.

My View:

class EditArticleView(LoginRequiredMixin, UpdateView):
    model = Article
    message = _("Your Article has been updated.")
    form_class = ArticleForm
    template_name = 'articles/article_update.html'


def form_valid(self, form):
    form.instance.user = self.request.user

    return super().form_valid(form)

def get_success_url(self):
    messages.success(self.request, self.message)
    return reverse('articles:list')

'''
def get_queryset(self):
    queryset = super(EditArticleView, self).get_queryset()
    queryset = queryset.filter(user=self.request.user)
    print(self.request.user)
    return queryset
'''

Solution

  • As an alternative you might also consider using the UserPassesTest mixing as described in the docs:

    from django.contrib.auth.mixins import UserPassesTestMixin
    
    class EditArticleView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
    
        def test_func(self):
            article = self.model.objects.get(pk=self.kwargs['pk'])
            return Group.objects.filter(user=self.request.user).filter(user=article.author).exists() # Or any other test you need
    
        # ... Your other view code