I'm trying to add a dropdown box of choices in my form. What I tried:
from django import forms
from .models import Car
class CarForm(forms.ModelForm):
owner_name = forms.CharField(max_length=100, label='Owner Name', required=True)
car_type = forms.ChoiceField(choices=Car.CarTypes.choices, label='Car Type', required=True)
class Meta:
model = Car
fields = ('owner_name', 'car_type')
It adds the car_type field to the form but it's not a dropdown for some reason (it's a regular empty box you could fill). The CarTypes looks like:
class CarTypes(models.TextChoices):
X = 'some_x'
Y = 'somy_y'
# ...
What could be the reason?
In my Car class I have: car_type = models.CharField(max_length=24, choices=CarTypes.choices, default=CarTypes.X). Could be it? I think CharField makes it empty box. But changing it to ChoiceField ends with: module 'django.db.models' has no attribute 'ChoiceField'. How to solve it?
I tried this approach but it uses a tuple instead of a class. From the example there I see they use tuple of two-value-tuples like (('a','A'),('b','B')) and I'm using class. Could it be the reason?
In my html I have:
<form method="post" class="form-group">
{% csrf_token %}
{% for field in form %}
<div class="form-group col-md-12 mb-3">
<label for="{{ field.label }}">{{ field.label }}</label>
<input type="text" class="form-control" id="{{ field.label }}" name="{{ field.name }}">
</div>
{% endfor %}
<hr class="mb-4">
<button type="submit" class="btn btn-secondary btn-lg btn-block">Submit New Car</button>
</form>
And the Car looks like:
class Car(models.Model):
class CarTypes(models.TextChoices):
X = 'some_x'
Y = 'somy_y'
# ...
owner_name = models.CharField(max_length=100,unique=True)
car_type = models.CharField(max_length=24, choices=CarTypes.choices, default=CarTypes.X)
def __str__(self):
return self.owner_name
Car. Django vesion?