【问题标题】:Django unclear 404Django 不清楚 404
【发布时间】:2020-01-29 00:01:11
【问题描述】:

编辑:自己找到了解决方案!

这就是我所做的。我很确定这不是最佳做法,但它对我有用。

class CommentCreateView(CreateView):

    def get(self, request, *args, **kwargs):
        context = {'form': CommentForm()}
        return render(request, 'news/add_comment_to_article.html', context)

    def post(self, request, *args, **kwargs):
        form = CommentForm(request.POST)
        if form.is_valid():
            article = get_object_or_404(Article, pk=kwargs.get('pk'))
            print(article)
            comment = form.save(commit=False)
            comment.post = article
            comment.save()
            return HttpResponseRedirect(reverse('news:article', kwargs={'article_id': article.pk}))

我有一个问题,在将我的视图(包括在下面)从基于函数的视图转换为基于类的视图后,我在尝试对一篇文章提交评论后不断收到错误消息(找不到页面 - 404)。这是为什么呢?

现在的观点:

class CommentCreateView(RedirectView):
    model = Comment
    form_class = CommentForm
    template_name = 'news/add_comment_to_article.html'

    def form_valid(self, *args, **kwargs):
        article = get_object_or_404(Article, pk=kwargs.get('pk'))
        comment = form.save(commit=False)
        comment.post = article
        comment.save()
        return HttpResponseRedirect(reverse('news:article', kwargs={'article_id': article.pk}))

和过去一样,基于功能(工作):

def add_comment_to_article(request, pk):
    article = get_object_or_404(Article, pk=pk)
    if request.method == "POST":
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = article
            comment.save()
            return HttpResponseRedirect(reverse('news:article', kwargs={"article_id": article.pk}))
    else:
        form = CommentForm()
    return render(request, 'news/add_comment_to_article.html', {'form': form})

意见表:

class CommentForm(forms.ModelForm):

    class Meta:
        model = Comment
        fields = ('author', 'text',)

【问题讨论】:

    标签: python django http-status-code-404 django-class-based-views


    【解决方案1】:

    使用FormView 代替RedirectView。 (我们可以看到RedirectView 没有form_valid 方法。)

    Django's official documentation 中了解有关 FormView 的更多信息。

    【讨论】:

    • 我尝试使用 CreateView 和 FormView,但我没有设法得到结果 :(
    • 那么这将是一个详细了解其中一个的好机会!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-24
    • 2013-03-05
    • 2013-02-28
    • 1970-01-01
    • 2020-08-22
    • 2020-11-15
    • 2016-03-22
    相关资源
    最近更新 更多