Home > Net >  Selectfield not showing options
Selectfield not showing options

Time:05-19

I have a field in my modelform where the user can choose the mealtype. But the form input does not work, when I click it, nothing happens. What I want to happen is to display a dropdown with the different meal types.

The model looks like this

class Recipe(models.Model):
   ...
    meal_type = {
        ('Breakfast', 'Breakfast'),
        ('Lunch', 'Lunch'),
        ('Dinner', 'Dinner')

    }
    meal = models.CharField(max_length=12, choices=meal_type, null=True)

My form looks like this

class RecipeForm(forms.ModelForm):
 ...
    meal = forms.CharField(widget=forms.Select(attrs={'class':'form-select'}))
    class Meta:
        model = Recipe
        ....

I have also tried to use "Choicefield" instead of "Charfield" but I can't get it to work.

EDIT This is how I render the form in the template

<form action='' method="POST"  hx-post='' hx-swap='outerHTML' >
{% csrf_token %}

{% for field in form %}
    <div >
        {{field}}
    </div>
{% endfor %}


<div class='htmx-indicator'>Loading...</div>
<div >
    <button class='htmx-inverted-indicator' style='margin-top:10px;' type='submit' >Save</button>
  </div>

{% if message %}
    <p>{{ message }}</p>
{% endif %}
Then I include this in the update template like
{% include 'recipe/komponents/forms.html' %}

CodePudding user response:

Try using square brackets [for, a, list] rather than curly braces {"which":denotes, "a": dictionary), eg,

meal_type = [
    ('Breakfast', 'Breakfast'),
    ('Lunch', 'Lunch'),
    ('Dinner', 'Dinner')
]

You also have widget defined as you would for a forms.form, not forms.ModelForm, which may be confusing the issue. In your form, try removing the meals =... line and replace with:

Class Meta:
    model = Recipe
    widgets = {
        'meal': forms.Select(attrs={'class':'form-select'}),
    }
  • Related