Saving multiple instances of same form in django -
in template user can add (with add button :) ) instance of same form (empty 1 ofc ) when click submit(save) ony last 1 entered being saved. views.py:
def form_valid(self, form): self.object = form.save() return httpresponseredirect(self.get_success_url())
template:
<form action="{{ action }}" class="form-horizontal form-inline" method="post" enctype="multipart/form-data"> {% csrf_token %} {% if object.id %} <legend>edit object2</legend> {% else %} <legend>add object2</legend> {% endif %} {{ form }} <div class="objects2"> {% objects2_form in form %} <div id="objects2-{{ forloop.counter0 }}"> </div> {% endfor %} </div> <div class="form-actions"> <a href="#" id="add-object2" class="btn btn-info add-object2" >add object2</a> <button type="submit" class="btn btn-primary">submit</button> </div> </form>
edit: i've decided it's easier post 1 object @ time , on save render same page. problem have 1(last) form shown on page instead of all. (all saved in db). , how show empty form last?
edit2: i've managed show all:
object2 = object2model.objects.all() return render_to_response('xxx.html', {'form': form, 'object2': object2}, context_instance = requestcontext(self.request))
so 1 thing remains.. how show empty form?? (without using formset)
the name
attributes of form's data tags repeated. so, example, last <input type="text" name="firstname">
overwrite previous fields same name="firstname"
name.
there not built-in way have same form fields render twice inside same <form/>
dom element.
i render forms.form
instances different <form/>
elements , have 1 joined submit <button onclick="submitallforms()">
calls javascript submit existing <forms/>
objects.
that cleanest way, server-side models.
so, on-load, select empty form dom element , copy it. then, when user selects add instance of form, can use copy template add form page. have number of same form way, no additional work.
then when user submits form, select <form>
dom elements , call .sumbit() on each. , server ever see regular forms.form
instances submitted.
Comments
Post a Comment