Django国家下拉菜单默认 [英] django countries dropdown default

查看:61
本文介绍了Django国家下拉菜单默认的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Django ModelForms。我有一个下拉选择器,允许用户选择国家。国家是预订模型的一部分,并使用django_countries定义。例如,

I am using Django ModelForms. I have a dropdown selector that allows users to select the country. The country is part of the booking model and is defined using django_countries. For example,

在models.py

In models.py

from django_countries import CountryField

class Booking(models.Model)
    name = models.charField(max_length=100)
    country = CountryField()

在views.py中,我希望能够在下拉菜单中设置默认的选定项,例如英国。我知道如何使用文本字段执行此操作,但是无法使其与CountryField()一起使用。例如,

In views.py I want to be able to set a default selected item in the drop down menu, for example 'United Kingdom'. I know how to do this with text fields, however cannot get it to work with the CountryField(). For example,

booking = BookingForm(initial={'name': 'mr majeika'}) //works
booking = BookingForm(initial={'country': 'United Kingdom'}) //does not work



<我希望外面有人可以指出正确的方向?

I was hoping someone out there may be able to point me in the right direction?

推荐答案

根据此处:

http://pypi.python.org/pypi/django-countries/1.0.1

CountryField基于Django的CharField,提供对应于官方ISO 3166-1国家列表的选择(,默认max_length为2

"CountryField is based on Django's CharField, providing choices corresponding to the official ISO 3166-1 list of countries (with a default max_length of 2)"

以及此处的CountryField的完整列表:

And the complete list of the CountryField here:

http://djangosnippets.org/snippets/1476/

可以试试看吗

booking = BookingForm(initial={'country': 'GB'})

这篇关于Django国家下拉菜单默认的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆