How to populate drop down choice from data base in django form

I want to try populating fields from the database in Django form, but it's showing me blankly. Can anyone give me an idea? Here I am sharing my code.

  class circleform(forms.ModelForm):
    class Meta:
    model = curd
    fields = ['Zone','Circle','circle_code','circle_address'] 
    
    widgets = {
        'Zone':forms.Select(attrs = {'class':'form-control'}),
        'Circle':forms.TextInput(attrs = {'class':'form-control'}),
        'circle_code':forms.TextInput(attrs = {'class':'form-control'}),
        'circle_address':forms.TextInput(attrs = {'class':'form-control'}),
    }     
    

I think you could use a field overriding like

class YourForm(forms.ModelForm):
    your_foreign_key_field_name = forms.ModelChoiceField(queryset=YourChoiceModel.objects.all()) 

    class Meta:
        ....

or in case you just want a form that reflect all your model's fields, try using Admin https://docs.djangoproject.com/en/4.1/intro/tutorial07/

If you are looking for a field that will populate your query based on a query then ModelChoiceField is what you are looking for. You can use it like that

class circleform(forms.ModelForm):
    your_field = ModelChoiceField(queryset="you query here to populate choice field")
    
   # ...      

but if you have some hard-coded choices that you want to populate then you can pass a choices=YOUR_CHOICES_TUPLE like that.

 class circleform(forms.ModelForm):
    class Meta:
    model = curd
    fields = ['Zone','Circle','circle_code','circle_address']
    YOUR_CHOICES = (
                ('', 'Select your zone'),
                ('1', 'First'), #First one is the value of the select option and the second is the displayed value in the option
                ('2', 'second'),
                )
    
    widgets = {
        'Zone':forms.Select(attrs = {'class':'form-control'}, choices=YOUR_CHOICES), # new

    }     
    
Back to Top