modelForm crispy formhelper and choices list datepicker not showing

1.7k Views Asked by At

I've searched through Stackoverflow for this and cannot find an answer.

I am trying to render a ModelForm using crispy forms and FormHelper to help me lay it out nicely. Everything was working fine when I was using the forms.Form library. but the main problem now is that the date picker and the choices field no longer have a dropdown list with the datepicker or the

So this is my forms.py file:

CITIES= (("London","London"), ("Istanbul","Istanbul"), ("Cape Town","Cape Town"))

class EntryForm(forms.ModelForm):
    class Meta:
        model = Items
        itemName = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'item name'}))
        ...
        date = forms.DateField(widget=forms.TextInput(attrs={'type': 'date'}),required=False)
        location =forms.ChoiceField(choices=CITIES, required=False)
        
        fields = ['itemName', 'date', 'location']

    def __init__(self, *args, **kwargs):
        super(EntryForm, self).__init__(*args, **kwargs)

        self.helper = FormHelper()
        self.helper.layout = Layout(
            'itemName',
             ...
             Row(
                 Column('date', css_class='form-group col-md-6 mb-0'),
                 Column('location', css_class='form-group col-md-6 mb-0'),
                 css_class='form-row'
             ),
        
             Submit('submit','Submit')
         )

My template file looks like this:


    {% extends 'base.html' %}
    {% load crispy_forms_tags %}
    
    {% block content %}
    
    <h1>Entry Form</h1>
    <br>
      {% crispy form %}
    <br>
   
    {% endblock %}

1

There are 1 best solutions below

1
YellowShark On

Not 100% certain if this is the issue, but I think you might just need to shift the fields to the EntryForm class, like so:

class EntryForm(forms.ModelForm):
    # Fields should go here, not under the Meta class:
    itemName = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'item name'}))
    ...
    date = forms.DateField(widget=forms.TextInput(attrs={'type': 'date'}),required=False)
    location =forms.ChoiceField(choices=CITIES, required=False)

    class Meta:
        model = Items    
        fields = ['itemName', 'date', 'location']