Cannot save a modelform using Django Crispy Forms

65 Views Asked by At

I cannot save my form because the payload is not formatted correctly.. I'm using HTMX for rendering the form in a modal

here's the code:

forms.py

class RecipeForm(forms.ModelForm):

    title = forms.CharField(
        label="Titolo",
    )

    method = forms.CharField(
        widget=forms.Textarea(),
        label="Procedimento",
    )

    tags = CustomTagsMultipleChoice(
        queryset=Tag.objects.all(),
        widget=forms.CheckboxSelectMultiple,
        label="Tag",
    )

    hero_image = forms.ImageField(
        label="Immagine",
    )

    class Meta:
        model = Recipe
        fields = ["title", "method", "tags", "hero_image"]

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.attrs = {
            "hx-post": reverse_lazy("recipes:recipe_create"),
            "hx-target": "#dialog",
        }
        self.fields["tags"].required = False
        self.fields["method"].required = False
        self.fields["hero_image"].required = False
        self.fields["tags"].label = False
        self.helper.layout = Layout(
            FloatingField("title"),
            FloatingField("method", css_class="fl-textarea"),
            "hero_image",
            InlineCheckboxes("tags"),
            Div(
                Submit("submit", "Salva"),
                Submit("button", "Cancella", css_class="btn btn-danger", data_bs_dismiss="modal"),
                css_class="text-end",
            ),
        )

views.py

@login_required
def recipe_create(request):
    if request.method == "POST":
        form = RecipeForm(request.POST,request.FILES)
        if form.is_valid():
            form.save()
            return HttpResponse(status=204, headers={"HX-Trigger": "recipeSaved"})
        form = RecipeForm(request.POST,request.FILES)
        context = {"recipe_form": form}
        return render(request, "recipes/partials/_recipe_create.html", context)
    form = RecipeForm()
    context = {"recipe_form": form}
    return render(request, "recipes/partials/_recipe_create.html", context)

_recipe_create.html

{% load crispy_forms_tags %}
<div class="modal-content">
    <div class="modal-header">
        <h5 class="modal-title">Aggiungi una ricetta</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Chiudi"></button>
    </div>
    <div class="modal-body">
        {% crispy recipe_form %}
    </div>
</div>

if I print request.POST I get this badly formatted payload

<QueryDict: {'------WebKitFormBoundaryIbg12MlAkITtzU0g\r\nContent-Disposition: form-data; name': ['"submit"\r\n\r\nSalva\r\n------WebKitFormBoundaryIbg12MlAkITtzU0g\r\nContent-Disposition: form-data; name="csrfmiddlewaretoken"\r\n\r\n0DWNbShUV0r8mFSPUNQaSQapC38FQFrMeOtmqFY64H4x3ReOuG7suKqUip7sSpqv\r\n------WebKitFormBoundaryIbg12MlAkITtzU0g\r\nContent-Disposition: form-data; name="title"\r\n\r\ntest\r\n------WebKitFormBoundaryIbg12MlAkITtzU0g\r\nContent-Disposition: form-data; name="method"\r\n\r\n\r\n------WebKitFormBoundaryIbg12MlAkITtzU0g--\r\n']}>

the form is not valid and re-rendered with the title field empty with errors as is a required field

any ideas? I've build another form with the same logic and it's working fine. The only difference is that this one includes an imagefield and so include a enctype="multipart/form-data"

Please help as I'm going mad.. thanks

I expect the form to be validated and saved to the DB

0

There are 0 best solutions below