Py学习  »  问与答

[精华] Django 1.6 Python 3.3 Jquery 如何在同一个页面识别和处理3个不同modelform递交的数据?

绿波畅游-weibo • 10 年前 • 4192 次点击  

这个页面是一个问题的细节页面,包括

  1. 问题标题,内容,该问题的所有评论,以及向该问题添加评论的表单qc_form;
  2. 该问题所有的回答条目,每个回答的所有评论,以及向该回答添加评论的表单ac_form;
  3. 最后是向这个问题添加回答的表单a_form.

当页面只有一个表单的时候,比如a_form,我知道如何在view.py中处理它.但像这种3个的,我就不太清楚了.在提交评论的时候,希望能够避免加载整个页面,只需更新评论部分的数据即可.

目前的问题是,在评论表单提交的内容会POST到Answer数据表里面.

源码在这里 http://note.youdao.com/share/?id=1f6cf3aa01188e2a35ed6edc2097c6ce&type=note

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/373
 
4192 次点击  
文章 [ 3 ]  |  最新文章 10 年前
Py站长
Reply   •   1 楼
Py站长    10 年前

@绿波畅游-weibo :)

绿波畅游-weibo
Reply   •   2 楼
绿波畅游-weibo    10 年前

@Django中国社区 非常感谢,该方法成功处理了这种情况!

Py站长
Reply   •   3 楼
Py站长    10 年前

有一种方法是: http://catherinetenajeros.blogspot.jp/2013/03/how-to-handle-multiple-forms-in-one-view.html

Sometimes we make two forms or more in one page which result to unnecessary output or error. To handle this problem, we have to put unique value in each form.

#page.html
<form method="POST">
    {{form1.as_p}}
    <input type="hidden" name="action" value="first">
    <input type="submit" value="Submit">
</form>

<form method="POST">
    {{form2.as_p}}
    <input type="hidden" name="action" value="second">
    <input type="submit" value="Submit">
</form>

<form method="POST">
    {{form3.as_p}}
    <input type="hidden" name="action" value="third">
    <input type="submit" value="Submit">
</form>

Notice that in every form I put <input type="hidden" name="action"> which has different value (first, second, third). This hidden value will be use in views.

#views.py
def myview(request):
    if request.method == 'POST':
        if request.POST['action'] == 'first':
            //do stuff here for form1

        elif request.POST['action'] == 'second':
            //do stuff here for form2

        elif request.POST['action'] == 'third':
            //do stuff here for form3

    return render(request, 'mypage.html')

In this way the system will know which form must be process.

This is only a basic sample. There are many ways to handle this kind of problem.