Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django form with two submit buttons . . . one requires fields and one doesn't

I think this should be a fairly straightforward question . . . I have ONE Django form with TWO different submit buttons. The first submit button is just for SAVING to the database whatever values are typed in to the form fields (so the user can come back and finish the form later if they want). I want the form fields to NOT be required when this first submit button is clicked. When the user clicks the second submit button, though, all fields should be required. Is there a way to do this? Or do I just have to duplicate the form once for each submit button?

like image 883
laurenll Avatar asked Feb 27 '16 06:02

laurenll


People also ask

How do you handle multiple submit buttons in the same form?

Let's learn the steps of performing multiple actions with multiple buttons in a single HTML form: Create a form with method 'post' and set the value of the action attribute to a default URL where you want to send the form data. Create the input fields inside the as per your concern. Create a button with type submit.

How do I stop multiple form submissions in Django?

Multiple form submission happens because when page refreshes that same url hits, which call that same view again and again and hence multiple entries saved in database. To prevent this, we are required to redirect the response to the new url/view, so that next time page refreshes it will hit that new url/view.

Does every form need a submit button?

If you don't have any submit button it is acceptable after all it is an element of form tag and if it is not required you may not add it with in form . This will not broke any web standard.

What is form Cleaned_data in Django?

form. cleaned_data returns a dictionary of validated form input fields and their values, where string primary keys are returned as objects. form. data returns a dictionary of un-validated form input fields and their values in string format (i.e. not objects).


1 Answers

The answer above works, but I liked this way better: Changing required field in form based on condition in views (Django)

I have two buttons:

<!-- simply saves the values - all fields aren't required unless the user is posting the venue -->
<input type="submit" name="mainForm" value="Save">

<!-- post the values and save them to the database - fields ARE required-->
<input type="submit" name="postVenue" value="Post Venue">

I make all form fields required=False by default and then have this in my view:

if 'postVenue' in request.POST:
    form = NewVenueForm(request.POST)
    form.fields['title'].required = True
    form.fields['category'].required = True
    # do this for every form field
                          
elif 'mainForm' in request.POST:     
    form = NewVenueForm(request.POST)

Thanks everyone!!

like image 81
laurenll Avatar answered Sep 25 '22 22:09

laurenll