Radio buttons in django Forms

Django

Django Problem Overview


I'm having difficulty settings up the forms.py file to include a radio or select button. I looked at the documentation but was having no luck applying the correct syntax.

Here is what I currently have in forms.py--

from django import forms

class PictureForm(forms.Form):
	like = forms.ChoiceField(???)
	name = forms.CharField()
	email = forms.EmailField()
	message = forms.CharField()	

And in my views.py --

from app.forms import PictureForm

def index2(request):
	if request.method == 'POST':
		form = PictureForm(request.POST)
		if form.is_valid():
			cd = form.cleaned_data
			Picture.objects.create(like=cd['like'], name=cd['name'], email=cd['email'], message=cd['message'])
		    return HttpResponseRedirect ('/thanks/')
    else:
    	form = PictureForm()
    return render_to_response('index2.html', {'form':form},)

How can I set up a set of radio buttons of 'value1', 'value2', 'value3'? How to do this with a select dropdown? Thank you.

Django Solutions


Solution 1 - Django

Look at setting the field's widget and choices when writing the form class.

CHOICES=[('select1','select 1'),
         ('select2','select 2')]

like = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect)

The default widget is a drop down select.

Solution 2 - Django

Remember to remove all the external styling, and then add the code below:

CHOICES = [('M','Male'),('F','Female')]
Gender=forms.CharField(label='Gender', widget=forms.RadioSelect(choices=CHOICES))

The above code generates Radio buttons.

In my case, I was using a style.css file which was forcing the radio button to render as a list.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDavid542View Question on Stackoverflow
Solution 1 - DjangodtingView Answer on Stackoverflow
Solution 2 - DjangoMohit SehgalView Answer on Stackoverflow