简体   繁体   中英

In a Django ModelForm, I want to display a CharField as a Select Field with defined choices

I am trying to follow the documentation on the Django site to overwrite the default formatting of the form. I have tried a number of solutions (all commented out and they give me an error). The non-commented section, works but just renders a select box without any choices. Could you please let me know what I am doing wrong?

def get_site_geographies():
    return Site.objects.values_list('site_geography', flat=True).distinct()

class SiteFilterForm(forms.ModelForm):
    class Meta:
        model = Site
        fields = ['site_geography', 'site_region', 'site_name']
        # field_classes = {
        #     'site_geography': forms.ChoiceField(choices=get_site_geographies())
        # }
        widgets = {
            'site_geography': forms.Select
        # widgets = {
        #    'site_geography': forms.ChoiceField(choices=get_site_geographies())
        # }

In models.py, this is the relevant model field that I am referring to:

class Site (models.Model):
    site_name = models.CharField(max_length=255)
    site_geography = models.CharField(max_length=255)
    site_region = models.CharField(max_length=255, blank=True)

The choices options takes an iterable. A list or tuple of 2-tuples, which would be of the format:

(value, value to display)

So, you need to iterate over your values and create this format.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM