2010-03-10 88 views
1

我在同一頁有3個表單,每個表單都有不同的提交。如:Django,表單有效問題

<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後腳本,但每個提交都將通過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

小紙條,你的「ONLY AJAX查詢」響應具有的'401'狀態代碼,這意味着'UNAUTHORIZED'與暗示有正確的授權它會被接受,瀏覽器可能會提示輸入密碼。 '403' Forbidden可能更適合這個用例。 – MattH 2010-03-10 12:09:00

+0

感謝您的提示,我將改爲403 :) – Hellnar 2010-03-10 12:16:15

+0

Duplicate:http://stackoverflow.com/questions/2374224/django-working-with-multiple-forms無論它是否是Ajax或無關緊要。 – 2010-03-10 15:51:38

回答

2

難道你不能只是在每個窗體w /一個標識符隱藏輸入,然後只是檢查你的看法?

<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(): 
     ...