没有模型的简单Django表单验证

时间:2016-11-11 15:50:36

标签: python django forms validation

我正在尝试使用自定义验证器在Django表单中显示内联验证:

def validate_true(value):
    if value != 'T':
        raise ValidationError('no', code='invalid')

class Test2016(forms.Form):
    CHOICES_1 = [
        ('T', True),
        ('F', False)
    ]
    q1 = forms.ChoiceField(choices=CHOICES_1, widget=forms.RadioSelect, label='1. Do you run or not?', help_text='', validators=[validate_true])

如果他们没有选择True,我希望它在表单中显示单击提交时答案错误。

此样式验证,但显然使用True / Value无线电选择选项。

django form validation

在模板中:

<form action="">
    {{form.as_p}}
    <input type="submit">
</form>

查看代码:

def compliance_questions_2016(request):
    year = datetime.datetime.now().year
    completed = False
    form = compliance_forms.Test2016(request.POST or None)
    context = {
        'year': year,
        'completed': completed,
        'form': form
    }
    return render(request, 'v2/pos/compliance_questions_2016.html', context)

0 个答案:

没有答案