Django не поднимает ошибку ValidationError на ModelChoiceField (виджет RadioSelect), если пользователь не выбрал ни один выбор
У меня есть форма, которая содержит ModelChoiceField poller_category
class PollersForm(forms.Form):
# Poller Category
poller_category = forms.ModelChoiceField(widget=forms.RadioSelect(attrs={
'class': 'poller-category-radio',
}), queryset=Categories.objects.all().order_by('poller_category'), label='Select a Category')
, который отображается следующим образом:
<!-- Poller Categories -->
<div class="fieldWrapper">
<div class="label">{{ form.poller_category.label_tag }}</div>
<div class="category-ctn">
{% for category in form.poller_category %}
<div class="category-wrapper">{{ category }}</div>
{% endfor %}
</div>
</div>
Теперь, если пользователь не выбрал ни одной категории и пытается отправить форму, ничего не происходит.
Это фактически означает, что форма действительна, не так ли? Если да, то почему не срабатывает redirect
?
Также если я выбираю вариант и отправляю, вызывается redirect
, но категория не заполняется в БД.
# create a form instance and populate it with data from the request:
form = PollersForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the remaining data in form.cleaned_data as required
poller_text = form.cleaned_data['poller_text']
poller_category = form.cleaned_data['poller_category']
poller_choice_one = form.cleaned_data['poller_choice_one']
poller_choice_two = form.cleaned_data['poller_choice_two']
# Get the user
created_by = request.user
# Save the poller to the database
p = Pollers(poller_text=poller_text,
poller_choice_one=poller_choice_one,
poller_choice_two=poller_choice_two,
poller_category=poller_category,
created_by=created_by)
p.save()
# redirect to a new URL:
return redirect(poller_success)
# if a GET (or any other method) we'll create a blank form
else:
form = PollersForm()
return render(request, 'pollinator/raise_poller.html', {'form': form})