从国家字段保存国家名称

时间:2019-06-20 08:43:56

标签: django django-models django-forms

我需要在我的表格(models.py)上的国家/地区选择字段:

class ContactForm(models.Model):
    first_name = models.CharField(max_length=10)
    Country = models.CharField(max_length=10)

还有我的forms.py:

from django_countries.fields import CountryField

class UserContact(forms.Form):
   first_name = forms.CharField(label='your first name', max_length= 10)    
   country = CountryField().formfield()

我的观点:

def get_data(request):

      form = UserContact()
      if request.method == 'POST':
             form =  UserContact(request.POST)
             if form.is_valid():
                    ContactForm.objects.create(**form.cleaned_data)
                    return render(request, '# some url', { 'form': form}

我的问题是,当我在管理页面中,在ContactForm模型中提交表单时,我有我输入的名字以及国家代码!不是国家的全名。 我不知道该怎么做。但是我知道我可以使用以下命令在shell中获取国家/地区名称:

>>>from django_countries import countries      
>>>dict(countries)['NZ'] 
>>>'New Zealand'

例如,我需要将新西兰保存在数据库中,而不是在新西兰。

1 个答案:

答案 0 :(得分:0)

建议保存国家代码而不是国家名称。因此,如下更改模型

models.py

from django.db import models
from django_countries.fields import CountryField

class ContactForm(models.Model):
    first_name = models.CharField(max_length=10)
    country = CountryField()

forms.py

from django_countries.fields import CountryField

class UserContact(forms.Form):
   first_name = forms.CharField(label='your first name', max_length= 10)
   country = CountryField().formfield()

保存表格后,您可以如下访问国家名称

obj = ContactForm.objects.get(pk=10) # some random pk
print(obj.country.name)
相关问题