Django中的干净方法中的Validationerror形式不起作用

时间:2017-03-27 07:45:03

标签: django django-forms

我正在尝试创建一个表单,使用户从radioselect中选择至少一个选项。但是我的干净形式方法不起作用。我希望有人可以通过我的forms.validationerror方法找出问题所在。

我尝试了下面的表格

credit_choices = (
    ('100',  '100  credits - $10'),
    ('200',  '200  credits - $18 - 11% Savings'),
    ('500',  '500  credits - $40 - 25% Savings'),
    ('1000', '1000 credits - $70 - 43% Savings'),
    ('2000', '2000 credits - $120 - 67% Savings'),
)

class CreditForm(forms.Form):

    credit = forms.ChoiceField(
        label='Select Amount of Credits to Purchase',
        choices=credit_choices,
        widget=forms.RadioSelect(),
        required=True
        )

我还尝试用两种方法的不同变体来清理表单。 clean_field()和clean()。我能够打印"无"或者选择的参数但是将跳过进入forms.Validationerror的步骤并进入页面上的Valueerror。

def clean_credit(self):
    credit = self.cleaned_data.get("credit")
    print credit
    if credit == None:
        print "test"
        raise forms.ValidationError("Please choose one")
    return credit

def clean(self):
    cleaned_data = super(CreditForm, self).clean()
    credit = self.cleaned_data.get("credit")
    print credit
    if not credit:
        print "test"
        raise forms.ValidationError("Please choose one")
    return cleaned_data

我的观点见下文。

class AddCredits(LoginRequiredMixin, FormMixin, TemplateView):
    form_class = CreditForm
    template_name = 'addcredit.html'

    def get_context_data(self, *args, **kwargs):
        context = super(AddCredits, self).get_context_data(*args, **kwargs)

        user = self.request.user
        usercred = get_object_or_404(UserCredit, user=user)

        context["user_credit"] = usercred.credit
        return context

    def post(self, request, *args, **kwargs):
        form = self.get_form()
        if form.is_valid():
            credit = form.cleaned_data.get("credit")
            request.session["credit"] = credit
            return self.form_valid(form)

    def get_success_url(self):
        return reverse('CheckOut')

我完全不知道为什么函数形式。跳过了验证。任何有用的建议都将深受赞赏。

1 个答案:

答案 0 :(得分:0)

在研究form_valid方法之后,我发现问题不在我的验证或form.py上。我不应该重写post方法,应该使用form_valid方法来获取发布的数据。

下面有更正的view.py,而不是post,我用form_valid方法交换它来收集发布的数据。以下内容现在有效。

class AddCredits(LoginRequiredMixin,FormView):
    template_name = 'addcredit.html'
    form_class = CreditForm

    def get_context_data(self, *args, **kwargs):
        context = super(AddCredits, self).get_context_data(*args, **kwargs)

        user = self.request.user
        usercred = get_object_or_404(UserCredit, user=user)

        context["user_credit"] = usercred.credit
        return context

    def form_valid(self, form):
        credit = form.cleaned_data.get("credit")
        self.request.session["credit"] = credit
        return super(AddCredits, self).form_valid(form)

    def get_success_url(self):
        return reverse('CheckOut')