Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/359.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django ForeignKey相关领域与ChoiceField本地化_Python_Django_Geodjango - Fatal编程技术网

Python Django ForeignKey相关领域与ChoiceField本地化

Python Django ForeignKey相关领域与ChoiceField本地化,python,django,geodjango,Python,Django,Geodjango,我有一个带有国家字段的自定义用户模型,我使用django cities的国家模型作为ForignKey。我还想对国家名称使用本地化。我无法导入django城市的alt_名称进行本地化,因此该选项不在表中。在我的forms.py中,我尝试使用 # forms.py from cities.models import Country from django.utils.translation import gettext_lazy as _ class SignupForm(UserCreati

我有一个带有国家字段的自定义用户模型,我使用django cities的国家模型作为ForignKey。我还想对国家名称使用本地化。我无法导入django城市的alt_名称进行本地化,因此该选项不在表中。在我的forms.py中,我尝试使用

# forms.py 
from cities.models import Country
from django.utils.translation import gettext_lazy as _

class SignupForm(UserCreationForm):
    c = Country.objects.all()
    country_choices = [(Country.objects.filter(id=c[i].id),  c[i].name ) for i in range(len(c)) ]
    country_choices_localize = [(c[0], _('{0}'.format(c[1]))) for c in country_choices]
    country = 
    forms.ChoiceField(choices=tuple(country_choices_localize), initial=None)

# view.py    
def signup(request):
    if request.method == 'POST':
        form = SignupForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            user.is_active = False
            user.save()
这似乎不起作用。如果form.is\u有效,Django将在表单验证时停止:我获取Country.objects.filterid=c[I].id的ValueError。表示MyUser.country必须是“country”实例。
在ChoiceField中使用本地化和国家/地区模型有解决办法吗?

不幸的是,您对列表的理解毫无意义。获取所有国家/地区,然后根据长度遍历一个范围,然后从原始列表中获取项目,然后再次从数据库中单独查询该项目?这确实不是Python的工作方式。而且也不需要单独的本地化列表理解。应该是:

country_choices_localised = [(i.id, _(i.name)) for i in c]

实际上,您会得到一个ValueError,因为表单将等待Country实例,而不是id为整数的整数。我建议您首先从表单字段中排除Country,然后添加一个名为Country_temp的临时字段,并使用此字段

class SignupForm(UserCreationForm):
    class Meta:
        exclude = ['country']
        model = YourUserModel

    def __init__(self, *args, **kwargs):
        super(SignupForm, self).__init__(*args, **kwargs)

        country_choices = [(country.id, _(country.name)) for country in Country.objects.all()] # get all countries o filter as you need
        country_temp = forms.ChoiceField(choices=country_choices, required=True)
在您看来,获得正确的实例

# view.py
def signup(request):
    if request.method == 'POST':
        form = SignupForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            user.is_active = False

            # validate some conditions to Country choice, if you need
            user.country = Country.objects.get(id=form.cleaned_data.get("country_temp"))
            user.save()

非常感谢。虽然,此解决方案不起作用,但i.id提供整数,但MyUser.country需要'country'实例。我遗漏了什么吗?大概是在保存表单时发生的。您需要显示代码和完整的回溯。