具有 ChoiceField 本地化的 Django ForeignKey 相关字段
Django ForeignKey related field with localization of ChoiceField
我有一个带有国家字段的自定义用户模型,我使用 django-cities 的国家模型作为 ForignKey。我还想对国家名称使用本地化。 (我无法导入 django-cities 的 alt_names 进行本地化,因此该选项已关闭 table)。在我的 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()
这似乎 work.Django 在表单验证时停止 if form.is_valid():
我得到 Country.objects.filter(id=c[i].id) 的 ValueError。说 MyUser.country 必须是 'Country' 实例。
是否可以解决在 ChoiceField 中使用本地化和国家/地区模型的问题?
不幸的是你的列表理解是胡说八道。你得到所有国家,然后根据长度循环一个范围,然后从原始列表中获取项目,然后再次从数据库中单独查询项目?这真的不是你的做法 Python。而且也不需要单独的本地化列表理解。它应该只是:
country_choices_localised = [(i.id, _(i.name)) for i in c]
您确实得到了 ValuError,因为表单会等待 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()
我有一个带有国家字段的自定义用户模型,我使用 django-cities 的国家模型作为 ForignKey。我还想对国家名称使用本地化。 (我无法导入 django-cities 的 alt_names 进行本地化,因此该选项已关闭 table)。在我的 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()
这似乎 work.Django 在表单验证时停止 if form.is_valid():
我得到 Country.objects.filter(id=c[i].id) 的 ValueError。说 MyUser.country 必须是 'Country' 实例。
是否可以解决在 ChoiceField 中使用本地化和国家/地区模型的问题?
不幸的是你的列表理解是胡说八道。你得到所有国家,然后根据长度循环一个范围,然后从原始列表中获取项目,然后再次从数据库中单独查询项目?这真的不是你的做法 Python。而且也不需要单独的本地化列表理解。它应该只是:
country_choices_localised = [(i.id, _(i.name)) for i in c]
您确实得到了 ValuError,因为表单会等待 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()