1

我在同一页面上有 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)

我不知何故需要找出张贴的表格。我怎样才能做到这一点 ?

4

1 回答 1

1

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

<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():
        ...
于 2010-03-10T16:08:42.593 回答