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

查看:25
本文介绍了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/

你能试试这个,看看它是否有效吗?

Can you try this and see if it works?

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

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

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