0

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>

1 Answers1

0

The problem here is the candidates choicelist that you are passing to the form during creation. The method you've used here is not appropriate and that's why the form can't get the choicelist and thus fails to validate. You have 2 options here. You can either define the candidates choicelist inside the forms.py and use it or use proper method to pass candidates choicelist to the form.

Option 1:

In forms.py :

     # dummy candidates list
    candidates = [
        (Male, 'Male'),
        (Female, 'Female'),
    ]


    class VoteForm(forms.Form):
        fields = ('Candidate')

        def __init__(self, *args, **kwargs):
            super(VoteForm, self).__init__(*args, **kwargs)

            self.fields['Candidate'] = forms.ChoiceField(choices=candidates, widget=forms.RadioSelect)

And in views.py just remove the candidates parameter from VoteForm() method.

Option 2:

There is already an answer here. You can check that out.

I have tested Option 1 and it works correctly.

KKD
  • 61
  • 5