使用 Modelform 选择值以填充组合框

Selecting values to populate the combobox using Modelform

我想获取列表中的所有国家/地区名称,以便将其设置为下拉列表的来源。

我的模型class如下所示

class UserExtForm(ModelForm):
    countries = Countries.objects.values('countryname').filter(countryname__isnull = False)

    class Meta:
     model = UserExtras
     fields=['phone','aboutme','countries']

我试图用所有国家/地区名称填充国家/地区对象,但是当显示 html 表单时,下拉列表中填充了文本 'Countries object'。请帮助我指出这里的内容。

非常感谢

在你的models.py

from django.db import models

class Article(models.Model):
    countries = models.CharField(max_length=200) //whatever

    def __str__(self):              # __unicode__ on Python 2
        return self.countries

取自the docs :

"It’s important to add str() methods to your models, not only for your own convenience when dealing with the interactive prompt, but also because objects’ representations are used throughout Django’s automatically-generated admin."