Reputation: 141
I have been using Django ModelForms in an attempt to display a number of fields as radio buttons. However, after following the guidance in Django Docs regarding the RadioSelect widget, no radio buttons are displaying in the browser. Can anybody explain why?
I have followed the instructions as set out in the Django Docs (https://docs.djangoproject.com/en/2.2/ref/forms/widgets/#radioselect). The relevant code is detailed below:
class ReviewForm(forms.ModelForm):
class Meta:
model = Review
fields = ['subject', 'feedback', 'mentorship', 'hiring', 'community']
class RawReviewForm(forms.Form):
RATINGS = (
('1', '1'),
('2', '2'),
('3', '3'),
('4', '4'),
('5', '5'),
)
subject = forms.CharField(label='')
feedback = forms.CharField(widget=forms.Textarea)
mentorship = forms.ChoiceField(widget=forms.RadioSelect(choices=RATINGS))
hiring = forms.ChoiceField(widget=forms.RadioSelect(choices=RATINGS))
community = forms.ChoiceField(widget=forms.RadioSelect(choices=RATINGS))
def review_create(request):
review_form = RawReviewForm()
if request.method == 'POST':
review_form = RawReviewForm(request.POST)
if review_form.is_valid():
review_form.save()
Review.objects.create(**review_form.cleaned_data)
return redirect(reviews)
context = {
'form': review_form
}
return render(request, 'reviews/review_form.html', context)
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend>Leave A Review</legend>
{{ form.as_p }}
{% for radio in form.mentorship %}
<div class="myradio">
{{ radio }}
</div>
{% endfor %}
{% for radio in form.hiring %}
<div class="myradio">
{{ radio }}
</div>
{% endfor %}
{% for radio in form.community %}
<div class="myradio">
{{ radio }}
</div>
{% endfor %}
</fieldset>
<button class="btn" id="submit" type="submit">Post Review</button>
</form>
Upvotes: 0
Views: 167
Reputation: 1
HTML must be fixed to {% for radio in RawReviewForm.mentorship %}
to view data.
Upvotes: 0
Reputation: 2675
From the docs:
The choices displayed on the widget are inherited from the
ChoiceField
and changingChoiceField.choices
will updateSelect.choices
.
So, just pass the choices to the ChoiceField
:
mentorship = forms.ChoiceField(widget=forms.RadioSelect, choices=RATINGS)
...
Upvotes: 1