【问题标题】:Go to newly created post转到新创建的帖子
【发布时间】:2020-08-21 20:24:03
【问题描述】:

一旦用户发布了有效帖子并按下了帖子,我希望他们被带到有效帖子。我用return redirect('post-detail', 18) 进行了测试。目前,一旦发布了有效帖子,就会加载 ID 为 18 的帖子。

我正在尝试获取新创建帖子的 ID。我要写的是return redirect('post-detail', id of newly created post)

由于这条线有效form.instance.author = self.request.user,我尝试了form.instance.id 但它没有达到预期的结果。

有人有什么建议吗?

class PostCreateView(LoginRequiredMixin, CreateView):
    model = Post
    fields = ['title', 'content']

def form_valid(self, form):
    form.instance.author = self.request.user

    return redirect('post-detail', 18)

    #print (form.instance.id)
    return redirect('post-detail', form.instance.id)

【问题讨论】:

    标签: python django python-3.x forms


    【解决方案1】:

    您没有保存表单,因此这意味着在那个时间点对象还没有主键。通常表单保存在基本的form_valid 方法中。

    您最好覆盖get_success_url,因为这是您应该“计算”要重定向到的网址的地方:

    from django.urls import reverse
    
    class PostCreateView(LoginRequiredMixin, CreateView):
        model = Post
        fields = ['title', 'content']
    
        def get_success_url(self):
            return reverse('post-detail', args=[self.object.pk])
    
        def form_valid(self, form):
            form.instance.author = self.request.user
            # will save the form and redirect to the success_url
            return super().form_valid(form)

    【讨论】:

    • 我现在收到错误消息 - 视图 blog.views.PostCreateView 没有返回 HttpResponse 对象。它返回 None 。
    • @RossSymonds:抱歉,打错了,你应该return super().form_valid() :)
    • 你能解释一下为什么 'return reverse('post-detail', args=[self.object.pk])' 有效,但 'return redirect ('post-detail', args=[self. object.pk])' 没有?
    • return super().form_valid(form)reverse 有什么问题?您需要像在代码片段的第一行一样导入它。
    • @RossSymonds: reverse 返回 路径(作为字符串),redirect 使用 reverse 并将其包装在 HttpRedirect 响应中。但是get_success_url本身应该返回一个包含路径的字符串,所以这里应该使用reverse
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多