【问题标题】:how to configure redirect in DeleteView如何在 DeleteView 中配置重定向
【发布时间】:2019-10-06 20:13:52
【问题描述】:

当我尝试删除一些评论时,它首先将我带到comment_delete_confirm.html,然后重定向到在success_url = '/blog/' 中链接的页面。当我将success_url更改为'post-detail'之类的东西时出现问题(因为我想在comment_delete_confirm返回帖子之后),它找不到这个页面,因为在brauser url中它看起来像这样:'127.0.0.1:8000/blog /post/18/comment_delete/post-detail'

这是我的 views.py 和 urls.py 文件:

class CommentDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
    model = Comment
    success_url = 'post-detail'
    # only the author can delete his post
    # if not author try to delete post it gives 403 forbidden
    def test_func(self):
        comment = self.get_object()
        if self.request.user == comment.user:
            return True
        return False

urlpatterns = [
    path('', PostListView.as_view(), name='blog-home'),
    path('user/<str:username>', UserPostListView.as_view(), name='user-posts'),
    path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'),
    path('post/new/', 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('post/<int:pk>/comment/', add_comment, name='comment-create'),
    path('post/<int:pk>/comment_update/', comment_update, name='comment-update'),
    path('post/<int:pk>/comment_delete/', CommentDeleteView.as_view(), name='comment-delete')
]

【问题讨论】:

    标签: django python-3.x django-views


    【解决方案1】:

    您需要使用实际的 URL,而不是名称。您可以为此使用reverse_lazy

    from django.urls import reverse_lazy
    
    class CommentDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
        model = Comment
        success_url = reverse_lazy('post-detail')
    

    编辑

    如果需要动态数据,可以重写get_success_url方法,而不是直接定义属性。在那里您可以访问self.object(因为在实际处理删除之前调用了该方法)。假设您的评论对象有一个 post 字段,它是 Post 的外键:

    def get_success_url(self):
        return reverse('post-detail', kwargs={'pk': self.object.post_id}) 
    

    【讨论】:

    • 我遇到了问题:'反向'post-detail',没有找不到参数。尝试了 1 种模式:['blog\\/post\\/(?P[0-9]+)\\/$']'。我下沉了,我必须将 'pk' 添加到 'success_url' 但如何?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-23
    • 2011-11-13
    • 2011-06-03
    • 2010-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多