Home > Software engineering >  How can I redirect user own 'post-detail' url in UpdateView class?
How can I redirect user own 'post-detail' url in UpdateView class?

Time:11-04

views.py

class PostUpdateView(LoginRequiredMixin , UpdateView):
        model =  Post
        template_name = 'blog/post_create.html'
        fields = ['title', 'content' ]
        # after post request url
        success_url = 'post-detail'

        def form_valid(self, form):
                form.instance.author = self.request.user
                return super().form_valid(form)
        
        def test_func(self):
                Post = self.get_object()
                if self.request.user == Post.author:
                    return True
                return False

This 'success_url' doesn't work

I need user, after updating their own post, to redirect back to their post details page

path('post/<int:pk>/', PostDetailview.as_view(), name='post-detail'

and i need one more help - how can send success messages after update

urls.py

from django.urls import path
from .views import (
    PostListView,
    PostDetailview,
    PostCreateView,
    PostUpdateView,
    PostDeleteView,
    about
)

urlpatterns = [
    path('', PostListView.as_view(), name='home'),
    path('post/<int:pk>/', PostDetailview.as_view(), name='post-detail'),
    path('post/create', PostCreateView.as_view(), name='post-create'),
    path('post/<int:pk>/update', PostUpdateView.as_view(), name='post-update'),
    path('post/<int:pk>/delete', PostDeleteView.as_view(), name='post-delete'),
    path('about/', about, name='about'),
]

CodePudding user response:

Here's a way of doing it right:

class PostUpdateView(LoginRequiredMixin , UpdateView):
        model =  Post
        template_name = 'blog/post_create.html'
        fields = ['title', 'content' ]
        # after post request url
        # success_url = 'post-detail' comment this line
        def get_success_url(self):
            return reverse("post-detail", args=[pk]) # you can replace pk

CodePudding user response:

You are assigning the url namespace (post-detail) not the url into the success_url as per the django document

https://docs.djangoproject.com/en/dev/ref/class-based-views/mixins-editing/#django.views.generic.edit.FormMixin.success_url

We should assign the url and that you can do by using either by reverse or reverse_lazy

As per your url.py you want to redirect on specific user post details page for that you should override the get_success_url method like Bichanna mentioned in his post.

def get_success_url(self):
    object_id = self.kwargs[self.pk_url_kwarg]
    return reverse_lazy('post-detail', kwargs={'pk': object_id})
  • Related