joseph
joseph

Reputation: 17

django authorization in class-based view

I'm trying to restrict access of CRUD pages to the owners, but I can't find the class-based view equivalent of "if request.user != post.author raise Http404". Thx for your time.

models.py

class Article(models.Model):
    title = models.CharField(max_length=255)
    body = models.TextField()
    date = models.DateTimeField(auto_now_add=True)
    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('article_detail', args=[str(self.id)])

views.py

class ArticleUpdateView(LoginRequiredMixin, UpdateView):
    model = Article
    fields = ['title', 'body']
    template_name = 'article_edit.html'
    login_url = 'login'

I tried the following (and many other combination arround those lines), but it isn't working.

def get(self, request, *args, **kwargs):
        if self.request.user == self.obj.author:
            raise Http404()

Upvotes: 1

Views: 67

Answers (2)

Ritesh Bisht
Ritesh Bisht

Reputation: 182

Youn can do something like this:-

class ArticleUpdateView(LoginRequiredMixin, UpdateView):
    model = Article
    fields = ['title', 'body']
    template_name = 'article_edit.html'
    login_url = 'login'

    def get(self, request, *args, **kwargs):
        self.obj = self.get_object()
        if self.request.user != self.obj.author:
            raise Http404()
        return super(ArticleUpdateView, self).get(request, *args, **kwargs)

Upvotes: 1

ruddra
ruddra

Reputation: 51978

I think you can override the get_queryset method to achieve this. For example:

class ArticleUpdateView(...):

 def get_queryset(self):
    queryset = super(ArticleUpdateView, self).get_queryset()
    return queryset.filter(author = self.request.user)

So, when a user tries to update an post which is not created by him, then he will not be able to get it because will not be able find the post object in Queryset provided by get_queryset method. For details, please SingleObjectMixin which is later sub-classed by UpdateView. FYI you don't need to override the get method for this implementation.

Upvotes: 0

Related Questions