django - 从国家字段中保存国家名称
问题描述
我的表格上需要国家选择字段,我的 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。
解决方案
建议保存国家代码而不是国家名称。所以,改变你的模型如下
模型.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)
推荐阅读
- arrays - 这里出现操作数预期的错误,错误标记是 +
- javascript - 如何将 javascript 函数传递给 webview?
- regex - 如何编写进行查找和替换的正则表达式模式?
- android - 第一次发送消息,为什么我不能再次发送消息(Android Socket 编程)
- node.js - npm 的问题 - internal/modules/cjs/loader.js:968
- rust - 如何修复“创建一个仍在使用时释放的临时对象”?
- javascript - 如果我滚动如何使其成为延迟加载的一个请求,则多个请求将成为 ajax
- flutter - 长按应用程序图标并显示弹出菜单
- r - 由于 isnan 模糊,安装 RFast 库时出错
- openlayers - Openlayers WMS - getGetFeatureInfoUrl 不是函数