Django处理意见表在同一页

2024-09-27 21:29:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道,是否有任何方法可以在一个模板上处理两个表单&;查看 其中一种形式不接受任何参数,而另一种形式接受参数 是的,一个表单是创建一个post的post表单 而另一个是comment表单,它实际使用一个参数(pk)来获取特定的post id并创建该对象

我尝试添加两个窗体,它们将在一个视图中创建两个对象 post对象及其post形式实际上运行良好 但是comment对象需要pk参数来过滤要创建的post对象 当我试图改变我的观点 从post\u create(请求)到def post\u create(请求,主键) 它引发了一个错误,说没有给出pk值

def post_create(request):
    if request.method=='POST':
        form = PostCreateForm(request.POST,request.FILES)
        comment=CommentForm(request.POST)
        post=Post.objects.get(id=pk)
        # comment=
        # print(form)
        if request.FILES:
            print('there is a file')
        else:
            print('no file')

        # if re
        if form.is_valid() or comment.is_valid():
            # c=comment.save(commit=False)
            psts = form.save(commit=False)
            psts.author = request.user
            # if comment:
            #     psts.comment.add(comment)
            # else:
            #     print('there is nothing')

            # psts.image =
            print(psts.image)
            psts.save()
            if comment.is_valid():
                comment = comment.save(commit=False)
                comment.post= post
                comment.user = request.user
                comment.save()
        else:
            print("form is not valid")
    else:
        form = PostCreateForm()
        comment=CommentForm()
    pst = Post.objects.all()
    query = request.GET.get('q')
    if query:
        pst = Post.objects.filter(title=query)


    context = {
        'pst':pst,
        'form': form,
        'comment':comment


    }
    return render(request,'posts/newsfeed.html', context)

我想在同一个视图和同一个模板中创建一个comment对象 或者如果你知道其他更好的解决方案,请告诉我


Tags: 对象form表单参数ifisrequestsave

热门问题