I have an original form (which is the result of three ModelForm
s) and I'm creating additional forms for two of those in the front-end.
Everything is working fine except for when saving the data. The originally rendered form saves correctly all the instances in the database. However, all the 'additionally added forms' won't save. In the form I have this button that with HTMX adds a new form:
<button type="button" class="btn btn-tertiary" hx-get="{% url 'buyandsell:create-product' %}" hx-target="#productforms" hx-swap="beforeend">Add new product</button>
This 'create-product' partial form corresponds to this view:
def create_product(request):
producto_form = ProductoForm()
imagen_form = ImagenForm()
context = {
'producto_form' : producto_form,
'imagen_form' : imagen_form
}
return render(request, 'buyandsell/partials/producto-form.html', context)
But I guess the view I need to change for saving the forms is the original main view. I tried iterating over 'producto_forms' but it doesn't let me (as I think that iteration refers to the fields of the form). This is the view function that is working well before adding additional products:
def anunciocreateview(request):
if request.method == "POST":
anuncio_form = AnuncioForm(request.POST or None)
producto_form = ProductoForm(request.POST or None)
imagen_form = ImagenForm(request.POST, request.FILES)
if all([anuncio_form.is_valid(), producto_form.is_valid(), imagen_form.is_valid()]):
anuncio = anuncio_form.save(commit=False)
anuncio.anunciante = request.user
anuncio.save()
producto = producto_form.save(commit=False)
producto.anuncio = anuncio
producto.save()
imagen = request.FILES.get('imagen')
if imagen:
Imagen.objects.create(producto=producto, imagen=imagen)
return HttpResponse(status=204, headers={'HX-Trigger' : 'eventsListChanged'})
else:
print(anuncio_form.errors)
print(producto_form.errors)
print(imagen_form.errors)
else:
anuncio_form = AnuncioForm()
producto_form = ProductoForm()
imagen_form = ImagenForm()
context = {
'anuncio_form' : anuncio_form,
'producto_form' : producto_form,
'imagen_form' : imagen_form
}
return render(request, 'buyandsell/formulario.html', context)
How can I make this view also look for additionally created forms and save them as well?