我无法从表单选择(国籍)中检索数据以检查值。
models.py
NATIONALITY_CHOICES = (('1', 'خليجي'), ('2', 'ليس خليجي'))
nationality = models.CharField(max_length=250,
choices=NATIONALITY_CHOICES, null=True)
当我在视图中检查我的字段时,它只会重定向thank_you_not!
views.py
def form_page(request):
if request.method == 'POST':
form = UserForm(request.POST)
if form.is_valid():
form.save()
if form.fields['nationality'].choices == 1:
return redirect('LandingPage:thank_you')
else:
return redirect('LandingPage:thank_you_not')
else:
form = UserForm()
posts = Article.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
return render(request, 'LandingPage/form_page.html', {'form': form, 'posts': posts,})
class UserForm(forms.ModelForm):
class Meta:
NATIONALITY_CHOICES = (('1', 'خليجي'), ('2', 'ليس خليجي'))
model = User
fields = ('first_name', 'second_name', 'E_mail', 'country', 'phone', 'phone_code','birthday', 'nationality',)
widgets = {
'first_name': forms.TextInput(attrs={'placeholder': 'الاسم الاول'}),
'second_name': forms.TextInput(attrs={'placeholder': 'الاسم الثاني'}),
'E_mail': forms.EmailInput(attrs={'placeholder': 'joe@schmoe.com'}),
'nationality': forms.Select(choices=NATIONALITY_CHOICES,attrs={'class': 'form-control'}),
}
我该如何解决?
答案 0 :(得分:3)
您可以通过检查cleaned_data
来查看表单中的字段值:
if form.is_valid():
nationality = form.cleaned_data['nationality']
# do something based on nationality value
以后编辑:
另外,查看如何定义选择,您可能会遇到与该if
语句不同的问题。
>>> one_str = '1'
>>> two_str = '2'
>>> one_str == 1
False
您已将字符串定义为选择值的标识符。将它们更改为int
以保持该逻辑不变。否则,您将永远没有field_valie == 1
评估为True
。