Search code examples
pythondjangodjango-modelsdjango-formsdjango-templates

How to make a select field using Django model forms (using set values)?


I recently switched from using simple forms in Django to model forms. I am now trying to use a select field in my form that has set field names (eg:Europe,North America,South America...) I thought I would just add a select input type to the for fields but it shows up as just a regular text input. The select field is supposed to be "continent". Does anyone know how to to d this??

class TripForm(forms.ModelForm):
    # city = forms.TextInput()
    # country = forms.TimeField()
    # description = forms.Textarea()
    # photo = forms.ImageField()
    class Meta:
        model = Trip
        fields = ('city', 'country', 'continent', 'description', 'photo')

        widget = {
            'city': forms.TextInput(attrs={'class': 'form-control'}),
            'country': forms.TextInput(attrs ={'class': 'form-control'}),
            'continent': forms.SelectMultiple(attrs= {'class':'form-control'}),
            'description': forms.TextInput(attrs = {'class': 'form-control'}),
            # 'photo': forms.ImageField(attrs = {'class': 'form-control'}),
        }

[![enter image description here][1]][1]

This is the form continent should show as a select.

Solution

  • Here you can use ModelChoiceField provided by django forms. Define a Country model containing all the countries, and use that as a QuerySet here. It will be also be dynamic that can be changed later.

    from django import forms
    from .models import Trip, Country
    
    class TripForm(forms.ModelForm):
        class Meta:
            model = Trip
            fields = ['name', 'country', 'start_date', 'end_date']
    
        
        country = forms.ModelChoiceField(
            queryset=Country.objects.all(),
            to_field_name='name',
            required=True,  
            widget=forms.Select(attrs={'class': 'form-control'})
        )