Gers
Gers

Reputation: 672

i want a button that Save a form to session

I have a form that is quite long, and I want my user to be able to save it in the session, do something else and go back to it later.

I was thinking of a button somewhere in the middle that activates the save-to-session action and leads another form to create a necessary object.

<a href="{% url 'tag:create_new_tag'%}">
   <button class="btn btn-primary" value="">
     Add New Tag
    </button>
</a>

The problem is that if i insert my button without any type (like in the code above), the form is submitted and my object saved to database, though I just want it to be saved in session. on the other hand, if i add a type=button attribute, the HTTP request will just be a GET, so I can't retrieve the fields that were complete so far.

how then is the best way to do that ?

Upvotes: 2

Views: 459

Answers (2)

Gers
Gers

Reputation: 672

I actually found out how to do what i had in mind thanks to another question found here How can I build multiple submit buttons django form?

So I put 2 different submit buttons that send the request to the same

<input class="btn btn-primary" name="add-new-tag" type="submit" value="Add New Grammar" />

<input class="btn btn-primary" name="submit-question" type="submit" value="Save" />

but then, in my view function that handles the form, I put a condition like

if 'add-new-tag' in form.data:
    #save the datas i need in session, and switch to a second form
    # when second form is completed and saved, redirect back to the 
    # main form and populate fields with data from session
else:
    #submit the main form

this allow me to use only one window

Upvotes: 0

Philip Tzou
Philip Tzou

Reputation: 6438

It seems you are using Bootstrap or similar framework. First of all you don't have to include a <button> inside of an <a> element, which is also a violation of W3C standard. Secondly, with Bootstrap, you can use just an a element in the meantime have it rendered as a button:

<a href="{% url 'tag:create_new_tag'%}" class="btn btn-primary" id="btn-add-new-tag">
  Add New Tag
</a>

It seems you also need to keep the form while opening the django URL 'tag:create_new_tag'. If open a new window/tab is acceptable:

<a target="_blank" href="{% url 'tag:create_new_tag'%}" class="btn btn-primary" id="btn-add-new-tag">
  Add New Tag
</a>

Furthermore, if you want to save the form while opening the URL, it had to be done with JavaScript:

var btnAddNewTag = document.getElementById('btn-add-new-tag');
var form = document.getElementById('your-form');
btnAddNewTag.addEventListener('click', function() {
    form.submit();
}, false);

Upvotes: 1

Related Questions