Para un proyecto que estoy desarrollando necesito construir un formulario de inscripción que va a guardar dos objetos al mismo tiempo, uno es campo foráneo de otro.
Esto con Django Admin se resuelve usando StackedInlineForm
, pero en formularios comunes no sé hacerlo. Necesito un formulario para poder pasar ese formulario a un modelo de página Wagtail.
He leído que se construye con formsets pero no sé usarlo, y deseo usar fieldsets
para agrupar correctamente los campos del formulario.
Este es el código del admin.py
:
class AffiliationInline(admin.StackedInline):
fieldsets = [
(None, {
'fields': ['person', 'affiliation', 'is_active'],
}),
(None, {
'fields': ['date_in', ],
}),
]
model = Affiliation
# suit_classes = 'suit-tab suit-tab-affiliation'
class AffiliatesAdmin(ImportExportModelAdmin, admin.ModelAdmin):
fieldsets = [
(_('Affiliate'), {
'classes': ('suit-tab suit-tab-general',),
'fields': ['name', 'logo', 'dni', 'attorney_name', 'position'],
}),
(_('Location'), {
'classes': ('suit-tab suit-tab-general',),
'fields': ['address', 'country', 'city', 'tel', 'fax', 'e_mail', 'web'],
}),
(_('Economic information'), {
'classes': ('suit-tab suit-tab-general',),
'fields': ['staff', 'interest', 'cause', 'economic_sector', 'economic_activity', 'other_interest'],
})
]
inlines = [AffiliationInline, ]
Este es el código que tengo en forms.py
:
class AffiliationInlineForm(forms.ModelForm):
class Meta:
model = Affiliation
fields =['person', 'affiliation']
class AffiliatesForm(forms.ModelForm):
class Meta:
model = Affiliates
fieldsets = '__all__'
¿Cómo puedo emular el comportamiendo del admin con formularios?
El resultado me debe dar otro formulario o un objeto único que pueda interactuar con una página de Wagtail.
Actualización:
He conseguido hacer el formulario junto con un formulario embebido, el formset
e imprimirlos en pantalla sin error alguno al imprimir:
def serve(self, request):
from .forms import AffiliatesForm, AffiliationInlineForm
AffiliationFormSet = inlineformset_factory(
Affiliates,
Affiliation,
form=AffiliationInlineForm,
fields=['person', 'affiliation', ],
extra=1
)
form = AffiliatesForm()
formset = AffiliationFormSet()
if request.method == 'POST':
form = AffiliatesForm(request.POST)
formset = AffiliationFormSet(request.POST)
if form.is_valid() and formset.is_valid():
form = form.save()
formset = formset.save()
return render(request, 'form_page_landing.html', {
'page': self,
'formset': formset,
'form': form,
})
else:
form = AffiliatesForm()
formset = AffiliationFormSet()
return render(request, 'form_page.html', {
'page': self,
'formset': formset,
'form': form,
})
Este es la plantilla para imprimir la página:
<form action="." method="POST" data-abide novalidate>
{% csrf_token %}
{# form.as_p #}
{{ formset.management_form }}
<ul class="tabs" data-tabs id="form-tabs">
<li class="tabs-title is-active"><a href="#affiliation" aria-selected="true">{% trans 'Affiliation' %}</a>
</li>
<li class="tabs-title"><a href="#affiliate">{% trans 'Affiliate' %}</a></li>
<li class="tabs-title"><a href="#location">{% trans 'Location' %}</a></li>
<li class="tabs-title"><a href="#economic">{% trans 'Economic information' %}</a></li>
</ul>
<div class="tabs-content" data-tabs-content="form-tabs">
<div class="tabs-panel is-active" id="affiliation">
<fieldset class="fieldset">
<legend>{% trans 'Affiliation' %}</legend>
{% for form in formset %}
<div class="row">
<div class="medium-6 columns">
<div class="row">
<div class="small-12 medium-3 columns">
<label for="middle-label id_{{ form.person.name }}" class="text-right middle">
{% if form.person.required %}
<span class="required">{{ form.person.label }}</span>
{% else %}
{{ form.person.label }}
{% endif %}
</label>
</div>
<div class="small-12 medium-9 columns">
{{ form.person }}
</div>
</div>
</div>
<div class="medium-6 columns">
<div class="row">
<div class="small-12 medium-3 columns">
<label for="middle-label id_{{ form.affiliation.name }}"
class="text-right middle">
{% if form.affiliation.required %}
<span class="required">{{ form.affiliation.label }}</span>
{% else %}
{{ form.affiliation.label }}
{% endif %}
</label>
</div>
<div class="small-12 medium-9 columns">
{{ form.affiliation }}
</div>
</div>
</div>
</div>
{% endfor %}
</fieldset>
</div>
<div class="tabs-panel" id="affiliate">
<fieldset class="fieldset">
<legend>{% trans 'Affiliate' %}</legend>
<div class="row">
<div class="small-12 medium-3 columns">
<label for="middle-label id_{{ form.name.name }}" class="text-right middle">
{% if form.name.required %}
<span class="required">{{ form.name.label }}</span>
{% else %}
{{ form.name.label }}
{% endif %}
</label>
</div>
<div class="small-12 medium-9 columns">
{{ form.name }}
</div>
</div>
<div class="row">
<div class="small-12 medium-3 columns">
<label for="middle-label id_{{ form.logo.name }}" class="text-right middle">
{% if form.logo.required %}
<span class="required">{{ form.logo.label }}</span>
{% else %}
{{ form.logo.label }}
{% endif %}
</label>
</div>
<div class="small-12 medium-9 columns">
{{ form.logo }}
</div>
</div>
<div class="row">
<div class="small-12 medium-3 columns">
<label for="middle-label id_{{ form.dni.name }}" class="text-right middle">
{% if form.dni.required %}
<span class="required">{{ form.dni.label }}</span>
{% else %}
{{ form.dni.label }}
{% endif %}
</label>
</div>
<div class="small-12 medium-9 columns">
{{ form.dni }}
{% if form.dni.help_text %}
<label for="id_{{ form.dni.name }}" class="help-text"
id="id_{{ form.dni.name }}_helptext">{{ form.dni.help_text }}</label>
{% endif %}
</div>
</div>
<div class="row">
<div class="small-12 medium-3 columns">
<label for="middle-label id_{{ form.attorney.name }}" class="text-right middle">
{% if form.attorney.required %}
<span class="required">{{ form.attorney.label }}</span>
{% else %}
{{ form.attorney.label }}
{% endif %}
</label>
</div>
<div class="small-12 medium-9 columns">
{{ form.attorney_name }}
</div>
</div>
<div class="row">
<div class="small-12 medium-3 columns">
<label for="middle-label id_{{ form.position.name }}" class="text-right middle">
{% if form.position.required %}
<span class="required">{{ form.position.label }}</span>
{% else %}
{{ form.position.label }}
{% endif %}
</label>
</div>
<div class="small-12 medium-9 columns">
{{ form.position }}
</div>
</div>
</fieldset>
</div>
<div class="tabs-panel" id="location">
<fieldset class="fieldset">
<legend>{% trans 'Location' %}</legend>
<div class="row">
<div class="small-12 medium-3 columns">
<label for="middle-label id_{{ form.address.name }}" class="text-right middle">
{% if form.address.required %}
<span class="required">{{ form.address.label }}</span>
{% else %}
{{ form.address.label }}
{% endif %}
</label>
</div>
<div class="small-12 medium-9 columns">
{{ form.address }}
</div>
</div>
<div class="row">
<div class="small-12 medium-3 columns">
<label for="middle-label id_{{ form.country.name }}" class="text-right middle">
{% if form.country.required %}
<span class="required">{{ form.country.label }}</span>
{% else %}
{{ form.country.label }}
{% endif %}
</label>
</div>
<div class="small-12 medium-9 columns">
{{ form.country }}
</div>
</div>
<div class="row">
<div class="small-12 medium-3 columns">
<label for="middle-label id_{{ form.city.name }}" class="text-right middle">
{% if form.city.required %}
<span class="required">
{{ form.city.label }}</span>
{% else %}
{{ form.city.label }}
{% endif %}
</div>
<div class="small-12 medium-9 columns">
{{ form.city }}
</div>
</div>
<div class="row">
<div class="small-12 medium-3 columns">
<label for="middle-label id_{{ form.tel.name }}" class="text-right middle">
{% if form.tel.required %}
<span class="required">{{ form.tel.label }}</span>
{% else %}
{{ form.tel.label }}
{% endif %}
</label>
</div>
<div class="small-12 medium-9 columns">
{{ form.tel }}
</div>
</div>
<div class="row">
<div class="small-12 medium-3 columns">
<label for="middle-label id_{{ form.fax.name }}" class="text-right middle">
{% if form.fax.required %}
<span class="required">
{{ form.fax.label }}/span>
{% else %}
{{ form.fax.label }}
{% endif %}
</label>
</div>
<div class="small-12 medium-9 columns">
{{ form.fax }}
</div>
</div>
<div class="row">
<div class="small-12 medium-3 columns">
<label for="middle-label id_{{ form.e_mail.name }}" class="text-right middle">
{% if form.e_mail.required %}
<span class="required">{{ form.e_mail.label }}</span>
{% else %}
{{ form.e_mail.label }}
{% endif %}
</label>
</div>
<div class="small-12 medium-9 columns">
{{ form.e_mail }}
</div>
</div>
<div class="row">
<div class="small-12 medium-3 columns">
<label for="middle-label id_{{ form.web.name }}" class="text-right middle">
{% if form.web.required %}
<span class="required">
{{ form.web.label }}</span>
{% else %}
{{ form.web.label }}
{% endif %}
</label>
</div>
<div class="small-12 medium-9 columns">
{{ form.web }}
</div>
</div>
</fieldset>
</div>
<div class="tabs-panel" id="economic">
<fieldset class="fieldset">
<legend>{% trans 'Economic information' %}</legend>
<div class="row">
<div class="small-12 medium-3 columns">
<label for="middle-label id_{{ form.staff.name }}" class="text-right middle">
{% if form.staff.required %}
<span class="required">{{ form.staff.label }}</span>
{% else %}
{{ form.staff.label }}
{% endif %}
</label>
</div>
<div class="small-12 medium-9 columns">
{{ form.staff }}
</div>
</div>
<div class="row">
<div class="small-12 medium-3 columns">
<label for="middle-label id_{{ form.interest.name }}" class="text-right middle">
{% if form.interest.required %}
<span class="required">{{ form.interest.label }}</span>
{% else %}
{{ form.interest.label }}
{% endif %}
</label>
</div>
<div class="small-12 medium-9 columns">
{{ form.interest }}
</div>
</div>
<div class="row">
<div class="small-12 medium-3 columns">
<label for="middle-label id_{{ form.cause.name }}" class="text-right middle">
{% if form.cause.required %}
<span class="required">{{ form.cause.label }}</span>
{% else %}
{{ form.cause.label }}
{% endif %}
</label>
</div>
<div class="small-12 medium-9 columns">
{{ form.cause }}
</div>
</div>
<div class="row">
<div class="small-12 medium-3 columns">
<label for="middle-label id_{{ form.economic_sector.name }}" class="text-right middle">
{% if form.economic_sector.required %}
<span class="required">{{ form.economic_sector.label }}</span>
{% else %}
{{ form.economic_sector.label }}
{% endif %}
</label>
</div>
<div class="small-12 medium-9 columns">
{{ form.economic_sector }}
</div>
</div>
<div class="row">
<div class="small-12 medium-3 columns">
{% if form.economic_activity.required %}
<label for="middle-label id_{{ form.economic_activity.name }}"
class="text-right middle">
<span class="required">
{{ form.economic_activity.label }}</span>
{% else %}
{{ form.economic_activity.label }}
{% endif %}
</label>
</div>
<div class="small-12 medium-9 columns">
{{ form.economic_activity }}
</div>
</div>
<div class="row">
<div class="small-12 medium-3 columns">
<label for="middle-label id_{{ form.other_interest.name }}" class="text-right middle">
{% if form.other_interest.required %}
<span class="required">{{ form.other_interest.label }}</span>
{% else %}
{{ form.other_interest.label }}
{% endif %}
</label>
</div>
<div class="small-12 medium-9 columns">
{{ form.other_interest }}
</div>
</div>
</fieldset>
</div>
</div>
<input class="float-center hollow button secondary" type="reset" name="{% trans 'Reset' %}"
style="margin-top: 1rem">
<input class="float-center hollow button secondary" type="submit" name="{% trans 'Send' %}"
style="margin-top: 1rem">
</form>
{% endblock %}
El problema es que a pesar de que he colocado ese instance=form.instance
para evitar un error que me decía que no se podía guardar el formulario por posible perdida de datos al no haberse guardado el objeto affiliates
, no he conseguido que se guarden los dos modelos encadenados, por lo cuál nunca se guarda alguno de los dos.
Una primera instancia, sin haber puesto esos instance
, pude guardar el formulario principal, afiliado, sin poder crear una afiliación al tiempo que estuviera encadenada al Afiliado y a la Membresía, osea, sólo se creaba el afiliado y nada más.
Estoy empezando a preguntarme si el problema es con django-smart-selects, que es el que uso para imprimis encadenados los dos selects del formset.
Como puedo resolver este problema?
Actualización:
He agregado el campo que faltaba en el formset: {{ form.id }}
, y obtuve el siguiente problema:
Se guardaba el formulario padre pero no guardaba los formularios hijos y me daba ese error.
Sin embargo cambie el orden de guardado, guardando primero el formulario incluido y luego el formulario padre:
if form.is_valid() and formset.is_valid():
formset = formset.save()
form = form.save()
Guardamos primero el formulario hijo, y ahí si el formulario padre, lógicamente.
Y con esto me aparece un error nuevo, pero tiene que ver con un paquete adicional que estoy usando: django-smart-selects.
instance
, por favor actualiza tu pregunta con el código actualizado