Hi,
I am trying to produce a template with many addresses (forms), where you can add, edit and remove them.
Am I doing something wrong with formsets? Here are my views:
@login_required
def addresses(request):
AddressesFormset = modelformset_factory(Address,
can_delete = True,
extra = 0,
exclude = ['user'])
log.debug('Queryset: %s', request.user.addresses.all())
if request.method == 'POST':
log.debug('Formset from POST')
formset = AddressesFormset(request.POST)
if formset.is_valid():
log.debug('Saving form')
formset.save()
log.debug('Fromset from queryset')
formset = AddressesFormset(queryset = request.user.addresses.all())
else:
log.debug('Form is not valid')
else:
log.debug('Fromset from queryset')
formset = AddressesFormset(queryset = request.user.addresses.all())
return render_to_response('accounts/addresses.html', locals(), context_instance = RequestContext(request))
@login_required
def add_address(request):
address = Address.objects.create(user = request.user)
address.save()
return HttpResponseRedirect('/accounts/addresses/')
And template:
{{ formset.management_form }}
{% for form in formset.forms %}
<table class="accountT">
<tr class="accountTT">
<td><p>Ulica, nr domu, mieszkania:</p></td>
<td>{{ form.street.errors }}{{ form.street }}</td>
</tr>
<tr class="accountTT">
<td><p>Miejscowość:</p></td>
<td>{{ form.city.errors }}{{ form.city }}</td>
</tr>
<tr class="accountTT">
<td><p>Kod pocztowy:</p></td>
<td>{{ form.zipcode.errors }}{{ form.zipcode }}</td>
</tr>
<tr class="accountTT">
<td><p>Telefon kontaktowy:</p></td>
<td>{{ form.phone.errors }}{{ form.phone }}</td>
</tr>
<tr>
<td><p>Usuń:</p></td>
<td>{{ form.DELETE }}</td>
</tr>
{{ form.id }}
</table>
{% endfor %}
Edit: The problem is that adding a form I have to save the formset (in add_address()). I would like to see how do you treat formsets properly. I don't understand it at all ;).
Thanks in advance, Etam.