[Django]-How to pass a complex url to a generic class Update view in django

3👍

You can filter the objects by overriding the get_object:

from django.shortcuts import get_object_or_404

class PostUpdateView(LoginRequiredMixin, UpdateView):
    model = Post
    fields = ['title','body']

    def get_object(self, *args, **kwargs):
        return get_obect_or_404(
            Post,
            publish__year=self.kwargs['year'],
            publish__month=self.kwargs['month'],
            publish__day=self.kwargs['day'],
            slug=self.kwargs['post'],
            author=self.request.user
        )

    def get_success_url(self):
        return reverse(
            'posts:post-update',
            args=[
                self.object.publish.year,
                self.object.publish.month,
                self.object.publish.day,
                self.object.slug
            ]
        )
    
    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

The author=self.request.user filter part, will ensure that if the logged in user is not the author, it will raise a HTTP 404 response instead of letting that user edit the post.

Leave a comment