視圖.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
這個 'success_url' 不起作用
我需要用戶在更新他們自己的帖子后重定向回他們的帖子詳細資訊頁面
path('post/<int:pk>/', PostDetailview.as_view(), name='post-detail'
我還需要一個幫助 - 如何在更新后發送成功訊息
網址.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'),
]
uj5u.com熱心網友回復:
這是一種正確的方法:
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
uj5u.com熱心網友回復:
您正在post-detail按照 django 檔案將 url 命名空間 ( ) 而不是 url分配到 success_url
https://docs.djangoproject.com/en/dev/ref/class-based-views/mixins-editing/#django.views.generic.edit.FormMixin.success_url
我們應該分配網址,您可以使用 byreverse或reverse_lazy
根據url.py您想要重定向到特定用戶帖子詳細資訊頁面,您應該覆寫像 Bichanna 在他的帖子中提到的 get_success_url 方法。
def get_success_url(self):
object_id = self.kwargs[self.pk_url_kwarg]
return reverse_lazy('post-detail', kwargs={'pk': object_id})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/347618.html
