【问题标题】:form validation redirection problems表单验证重定向问题
【发布时间】:2021-10-10 13:58:39
【问题描述】:

您好,我正在使用 django 在帖子上添加 cmets,我将信息直接保存在数据库中,这操作成功,但是在提交帖子后,它应该与评论重定向到同一页面上,但是表单继续重新提交请帮忙?

views.py

class PostDetailView(DetailView):
    def get(self, request, slug, *args, **kwargs):
        post = Post.objects.get(slug=slug)
        form = CommentForm()

        comments = Comment.objects.filter(post=post).order_by('-date_created')

        context = {
            'post':post,
            'form': form,
            'comments': comments
        }
        return render(request, 'my_news/post_detail.html', context )
    
    def post(self, request, slug, *args, **kwargs):
        post = Post.objects.get(slug=slug)
        form = CommentForm(request.POST)

        if form.is_valid():
            new_post = form.save(commit=False)
            new_post.name = request.user
            new_post.post= post
            new_post.save()

        comments = Comment.objects.filter(post=post).order_by('-date_created')

        context = {
            'post':post,
            'form': form,
            'comments':comments
        }
        return render(request, 'my_news/post_detail.html', context )

【问题讨论】:

    标签: python html django bootstrap-4


    【解决方案1】:

    通过上下文发送的表单包含之前发布的评论的数据。如果要显示空表单,则必须使用空表单。

    context = {
        'post': post,
        'form': CommentForm(),
        'comments': comments
    }
    

    希望我能正确理解您的问题

    【讨论】:

    • 是的,它工作正常,非常感谢!
    • 如果有帮助,您可以接受我的回答 ;-)
    猜你喜欢
    • 2016-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多