首页 > 解决方案 > 从国家字段中保存国家名称

问题描述

我的表格上需要国家选择字段,我的 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'

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

标签: djangodjango-modelsdjango-forms

解决方案


建议保存国家代码而不是国家名称。所以,改变你的模型如下

模型.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()

表格.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)

推荐阅读