views:

81

answers:

1

Hello

I have 3 forms at the same page and each has a different form submit. Such as:

<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>

For the sake of simplicity, I didn't include the ajax post scripts, but each submit will be queried via ajax.

Now I want to do processing all at the same page, /profile/update/ For this I have to check which form is posted. If posted and valid give some response, if not give another response.

@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)

I somehow need to find out what form is posted. How can I do this ?

+1  A: 

Couldn't you just put a hidden input in each form w/ an identifier, and then just check for that in your view?

<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>

and then in the view:

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