开发者

Radio buttons in django Forms

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.


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

from django import forms

class PictureForm(forms.Form):
    CHOICES = [
        ('1', 'Option 1'),
        ('2', 'Option 2'),
    ]
    like = forms.ChoiceField(
        widget=forms.RadioSelect,
        choices=CHOICES, 
    )
  • The default widget of ChoiceField is a drop down select.
  • The choices argument has the same format as the one of a model field.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜