【问题标题】:my Django form not validating when using __init__ for a dynamic Radio field将 __init__ 用于动态 Radio 字段时,我的 Django 表单未验证
【发布时间】:2019-09-20 02:04:52
【问题描述】:

我编写了一个带有单选按钮的表单,我在初始化表单时提供了它的值。表单正在完美显示,但是当我需要使用通过表单提交的值时,我不能,因为它没有进行验证。

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)

编辑。

HTML 代码

<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>

【问题讨论】:

    标签: django python-3.x django-forms


    【解决方案1】:

    这里的问题是您在创建期间传递给表单的 candidates 选择列表。您在此处使用的方法不合适,这就是表单无法获取选择列表从而无法验证的原因。 您在这里有 2 个选项。您可以在 forms.py 中定义 candidates 选择列表并使用它,也可以使用适当的方法将 candidates 选择列表传递给表单。 p>

    选项 1:

    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)
    

    而在 views.py 中,只需从 VoteForm() 方法中删除候选人参数即可。

    选项 2

    已经有答案here。你可以去看看。

    我已经测试了选项 1,它可以正常工作。

    【讨论】:

    • 但我不想将表单与模型链接起来,我只是想使用用户提交的值。反正我试过你的方法,没用。
    • 好的,我正在测试这个。
    • 我已经更新了我的答案。如果您解决了问题,请通知我。
    猜你喜欢
    • 2020-11-27
    • 1970-01-01
    • 2023-04-09
    • 2016-04-08
    • 1970-01-01
    • 2021-10-24
    • 2011-02-24
    • 1970-01-01
    • 2016-08-21
    相关资源
    最近更新 更多