Django,形成有效的问题

时间:2010-03-10 12:01:55

标签: ajax django django-forms django-views

我在同一页面上有3个表单,每个表单都有不同的表单提交。如:

<h1>Address</h1>
<form method="post" id="adress_form" action=/profile/update/>
{{ form_address.as_p }}

<p><button type="submit">Save</button></p>
</form>

<h1>Email Change</h1>
<form method="post" id="email_form" action=/profile/update/>
{{ form_email.as_p }}

<p><button type="submit">Save</button> </p>
</form>

<h1>Password Change</h1>
<form method="post" id="password_form" action=/profile/update/>
{{ form_password.as_p }}

<p><button type="submit">Save</button></p>
</form>

为了简单起见,我没有包含ajax post脚本,但是每个提交都将通过ajax进行查询。

现在我想在同一页面处理/profile/update/ 为此,我必须检查发布的表格。如果发布并有效给出一些回复,如果没有给出另一个回复。

@login_required
def profile_update_view(request):
    if request.method == 'POST' and request.is_ajax()::
        user = request.user
        form_adress = AdressForm(request.POST)
        form_email = EmailForm(request.POST)
        form_password = PasswordChangeForm(request.POST)

        if <CHECK IF THE SUBMIT IS AN ADDRESS FORM>
            if form_adress.is_valid():
                #update and return a json response object with "adress updated successfully." for ajax
            else:
                answer = {'answer': "Couldn't update. Your form is not valid"}  
                return HttpResponse(simplejson.dumps(answer), mimetype="application/json")

        if <CHECK IF THE SUBMIT IS AN EMAIL FORM>
            if form_email.is_valid():
                #update and return a json response object with "email updated successfully." for ajax
            else:
                answer = {'answer': "Couldn't update. Your form is not valid"}  
                return HttpResponse(simplejson.dumps(answer), mimetype="application/json")

        if <CHECK IF THE SUBMIT IS AN PASSWORD FORM>
            if form_password.is_valid():
                #update and return a json response object with "password changed successfully." for ajax
            else:
                answer = {'answer': "Couldn't update. Your form is not valid"}  
                return HttpResponse(simplejson.dumps(answer), mimetype="application/json")
    else:
        return HttpResponse(u"ONLY AJAX QUERIES PLEASE", mimetype="text/plain", status=403)

我不知何故需要找出发布的表格。 我怎么能这样做?

1 个答案:

答案 0 :(得分:2)

难道你不能只用一个标识符在每个表单中放入一个隐藏的输入,然后在你的视图中检查它吗?

<h1>Address</h1>
<form method="post" id="adress_form" action=/profile/update/>
<input type="hidden" name="_address" />
{{ form_address.as_p }}

<p><button type="submit">Save</button></p>
</form>

然后在视图中:

if '_address' in request.POST:
    if form_adress.is_valid():
        ...