Home > Enterprise >  How to create combobox with django model?
How to create combobox with django model?

Time:10-06

I want to create something like a combo box with django model, but i don't find any field type to do that. something like this: enter image description here

CodePudding user response:

Simply you can do this in models.py:

class Student(models.Model):
    select_gender = (
        ('Male', 'Male'),
        ('Female', 'Female'),
        ('Other', 'Other'),
    )
    student_name = models.CharField(max_length=100)
    student_gender = models.CharField(max_length=8, choices=select_gender)

In forms.py file, do this:

class StudentForm(forms.ModelForm):
    class Meta:
        model = Student
        fields = '__all__'
        widgets = {
            'student_name'  :   forms.TextInput(attrs={'class':'form-control'}),
            'student_gender'  :   forms.Select(attrs={'class':'form-control'})
        }

This is the way you can do.

  • Related