Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Radio buttons in django Forms

Tags:

django

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.

like image 252
David542 Avatar asked May 08 '11 01:05

David542


1 Answers

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.

like image 79
dting Avatar answered Sep 24 '22 02:09

dting