gpt4 book ai didi

python - django-国家/地区下拉列表不显示

转载 作者:行者123 更新时间:2023-12-02 11:44:18 28 4
gpt4 key购买 nike

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 下拉列表,但我什么也没看到。我没有收到任何错误。

提前致谢。

最佳答案

According to the documentation ,模块中有一个 2 元组的元组可用于填充您的字段:

Get the countries from Python

Use the django_countries.countries object instance as an iterator of ISO 3166-1 country codes and names (sorted by name).

所以以下应该有效:

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

编辑:经过讨论,我发现操作代码读得太快,完全搞混了。事实上,您需要创建一个 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 .

关于python - django-国家/地区下拉列表不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23726411/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com