Django - Creando formulario para editar múltiples instancias de modelo
Nota: principiante de Django / Python, espero que esta pregunta sea clara
Necesito crear un formulario donde se puedan editar varias instancias de un modelo a la vez en un solo formulario y enviarlas al mismo tiempo.
Por ejemplo, tengo dos modelos, Invitar e Invitado, donde se pueden asociar varios Invitados con una sola Invitación. Necesito un formulario único en el que pueda editar detalles particulares de todos los Invitados adjuntos a la invitación, enviarlos al mismo tiempo y guardarlos en la base de datos.
He visto algunas sugerencias sobre el usoformas crujientes, pero no he logrado que funcione.
He creado un formulario que proporciona ciertas entradas:
from django import forms
from app.models import Guest
class ExtraForm(forms.ModelForm):
diet = forms.CharField(max_length=128, required=False)
transport = forms.BooleanField(initial=False)
# An inline class to provide additional information on the form.
class Meta:
# Provide an association between the ModelForm and a model
model = Guest
fields = ('diet', 'transport')
Mi punto de vista consiste en:
def extra_view(request, code):
invite = get_invite(code)
# Get the context from the request.
context = RequestContext(request)
# Get just guests labelled as attending
guests_attending = invite.guest_set.filter(attending=True)
if request.method == 'POST':
form = ExtraForm(request.POST)
print(form.data)
# Have we been provided with a valid form?
if form.is_valid():
# Save the new category to the database.
# form.save(commit=True)
print(form)
return render(request, 'weddingapp/confirm.html', {
'invite': invite,
})
else:
# The supplied form contained errors - just print them to the terminal for now
print form.errors
else:
# # If the request was not a POST, display the form to enter details.
GuestForm = ExtraForm()
return render_to_response('weddingapp/extra.html',
{'GuestForm': GuestForm, 'invite': invite, 'guests_attending': guests_attending}, context)
Y finalmente, mi forma:
<form id="extra_form" method="post" action="{% url 'weddingapp:extra' invite.code %}">
{% csrf_token %}
{% for guest in guests_attending %}
<fieldset class="form-group">
<h3>Form for {{ guest.guest_name }}</h3>
{% for field in GuestForm.visible_fields %}
{{ field.errors }}
<div>
{{ field.help_text }}
{{ field }}
</div>
{% endfor %}
</fieldset>
{% endfor %}
{{ form.management_form }}
<table>
{% for form in form %}
{{ form }}
{% endfor %}
</table>
<input type="submit" name="submit" value="Submit"/>
</form>
Algún consejo