Search code examples
djangodjango-formsdjango-crispy-forms

Django - crispy form not showing


I'm trying to render this form:

class LoadForm(forms.Form):
    class Meta:
        model = Load

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_tag = False
        self.helper.layout = Layout(
            Row(
                'whouse',
                'supplier',
                'company',
                'product',
                'quantity',
                'unit_price',
                'load_date',
            )
        )

with the following view:

def load(request):
    form = LoadForm()
    context = {
        'form': form,
        'title': 'Nuovo Carico',
    }

    return render(request, 'warehouse/load.html', context)

and the following template:

{% extends "masterpage.html" %}
{% load static %}

{% block headTitle %}
<title>{{title}}</title>
{% endblock %}

{% block contentHead %}
{% endblock %}

{% block contentBody %}
{% load document_tags %}
{% load custom_tags %}
{% load crispy_forms_tags %}

<FORM method="POST" autocomplete="off">
    {{ form.media }}
    {% csrf_token %}

    <div class="alert alert-info">
        {{ title }}
    </div>
    {% crispy form %}
    <input type="submit" class="btn btn-primary margin-left" value="CARICA">


</FORM>

{% endblock %}

For some strange reason the form will not show up, I just see the title and the input button. I've tried the very simple form.as_p with no crispy, but still nothing...

By looking at the sourse code on the browser I see there is a div with class 'form-row' but not form in it...

looks strange.

Any help?

thank you very much.

Carlo


Solution

  • Your form class is defined as follows: class LoadForm(forms.Form): Note that here this is a Form and not a ModelForm hence using a Meta class and specifying model makes no difference. Instead you want to use a ModelForm [Django docs] and you also need to specify either fields or exclude in the Meta:

    class LoadForm(forms.ModelForm): # `ModelForm` here
        class Meta:
            model = Load
            fields = '__all__' # All fields
        
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            self.helper = FormHelper()
            self.helper.form_tag = False
            self.helper.layout = Layout(
                Row(
                    'whouse',
                    'supplier',
                    'company',
                    'product',
                    'quantity',
                    'unit_price',
                    'load_date',
                )
            )