这是这个问题的第三次迭代,因为错误已经解决了。 (在少数人的感激帮助下)。为了避免混淆到底发生了什么,我觉得有必要重新发布更新的细节。
我使用Django 1.6.4。
我试图在Django中使用django-国家申请,但是没有显示下拉列表。我没有错误,但下面的survey.html页面并没有显示国际标准化组织3166-1国家名单的预期下拉列表。
我在这个项目的虚拟环境中通过pip安装了django-countries 2.1.2。它已被添加到已安装的应用程序中。
INSTALLED_APPS
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'polls',
'survey',
'django_countries',
)models.py
from django.db import models
from django_countries.fields import CountryField
class Person(models.Model):
country = CountryField()
def __unicode__(self):
return self.country views.py
from django.shortcuts import render
from django.db import models
from django_countries.fields import CountryField
from models import SexChoice, AgeChoice, RelationshipStatusChoice, Person
def survey(request):
age = AgeChoice()
sex = SexChoice()
relationship = RelationshipStatusChoice()
country = Person()
return render(request, 'survey.html', {
'age': age,
'sex': sex,
'relationship': relationship,
'country': country,
})survy.html
<html>
<body>
<h1>Experiment Survey</h1>
<form action="" method="post">
{% csrf_token %}
<h3>What age are you?</h3>
{{age.as_p}}
<h3>What sex are you?</h3>
{{sex.as_p}}
<h3>What is your current relationship status?</h3>
{{relationship.as_p}}
<h3>What country are you from?</h3>
{{country.as_p}}
<input type="submit" value="Submit" />
</form>
</body>
</html>我以为这会给我一个country.as_p下降,但我什么也没看到。我没有任何错误。
提前谢谢。
发布于 2014-05-18 20:22:39
根据文件,模块中有一个2元组的元组可以填充您的字段:
从Python那里得到国家 使用
django_countries.countries对象实例作为ISO3166-1国家代码和名称的迭代器(按名称排序)。
因此,以下几点应能奏效:
from django.db import models
from django_countries.fields import CountryField
from django_countries import countries
class Person(models.Model):
country = CountryField(choices=list(countries))
def __unicode__(self):
return self.country编辑:经过讨论,我把OP代码读得太快完全搞混了。实际上,您需要创建一个Form,而不是直接在模板中使用您的模型:
class SurveyForm(forms.Form):
age = forms.CharField()
sex = forms.CharField()
relationship = forms.CharField()
country = forms.CountryField(choices=list(countries))
#####
def survey(request):
form = SurveyForm()
return render(request, 'survey.html', {'form': form})
#####
My whole form:
{{ form.as_p }}正如我在聊天中所说的,进一步的解释可在文档中找到。。
发布于 2014-07-03 09:03:06
你需要这张表格:
class SurveyForm(forms.Form):
age = forms.CharField()
sex = forms.CharField()
relationship = forms.CharField()
country = forms.ChoiceField(choices=list(countries))不需要在表单类中使用ChoiceField()。CountryField()用于模型。
https://stackoverflow.com/questions/23726411
复制相似问题