I have written a form which has a Radio Button, whose values I provide when I initialize the form. The form is being displayed perfectly but when I need to use the values submitted through the form, I cannot, because it is not validating.
forms.py
from django import forms
class voteForm(forms.Form):
def __init__(self,candidates, *args, **kwargs):
super(voteForm,self).__init__(*args, **kwargs)
self.fields['Candidate'] = forms.ChoiceField(choices=candidates, widget=forms.RadioSelect)
views.py
from django.shortcuts import render,redirect
from register.models import Candidate, Voter
from voting.models import Vote
from voting.forms import voteForm
from django.http import HttpResponse
def index(request):
context={}
if request.method=='POST':
form = voteForm(request.POST)
if form.is_valid():
# do something with data
return HttpResponse('Success')
voterid=1
context['voter']=Voter.objects.get(id=voterid)
request.session['id']=voterid
candidates=Candidate.objects.filter(region=context['voter'].region).values_list('id','name')
form = voteForm(candidates)
context['form']=form
return render(request,'voting/index.html',context)
Edit.
HTML code
<h1>Vote</h1>
{{ voter.name }}
{{ voter.region }}
<form action="/vote/" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit">
</form>