This is the third iteration of this question as errors have been solved(在少数人的感谢帮助下)。为了避免混淆到底发生了什么,我觉得有必要重新发布更新的细节。
我正在使用Django 1.6.4。
我正在尝试将django-countries application与Django一起使用,但下拉列表未显示。我没有收到任何错误,但下面的survey.html页面未显示ISO 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
下拉但我什么也看不见。我没有任何错误。
提前致谢。
答案 0 :(得分:3)
According to the documentation,模块中有一个2元组的元组可以填充你的字段:
从Python获取国家/地区
使用
django_countries.countries
对象实例作为ISO 3166-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 }}
正如我在聊天中所说,further explication are available in the documentation。
答案 1 :(得分:2)
您需要以下表格:
class SurveyForm(forms.Form):
age = forms.CharField()
sex = forms.CharField()
relationship = forms.CharField()
country = forms.ChoiceField(choices=list(countries))
不需要在表单类中使用ChoiceField()。 CountryField()用于模型。