简体   繁体   English

在Django中验证ModelForm的单个字段

[英]Validate single field of ModelForm in Django

I am having trouble validating a single field in Django. 我在验证Django中的单个字段时遇到问题。 What I have is the following: 我有以下内容:

class MoForm(ModelForm):
  def check_for_zero_cost(self):
    cost = self.cleaned_data['total_cost']
    if cost <= 0:
      raise forms.ValidationError("You value is less than zero")
    return cost

I get an exception when I attempt to validate. 尝试验证时出现异常。 This comes out as 这出来

global name 'forms' is not defined

I tried ValidationError("You value is less than zero") without the point to forms , but this raise an exception and what I want is just an error to be added to the form error list. 我尝试了ValidationError("You value is less than zero")没有指向forms的指向,但是这引发了异常,而我想要的只是将要添加到表格错误列表中的错误。 The think the reason I am getting this errors is because I dont have forms.ModelForm as the first argument in my class. 我收到此错误的原因是因为我没有forms.ModelForm作为类中的第一个参数。 If I do this then I get the following error: 如果执行此操作,则会出现以下错误:

name 'forms' is not defined

Can anyone help? 有人可以帮忙吗?

You shouldn't write your own method to validate individual form field. 您不应该编写自己的方法来验证单个表单字段。 You should use clean_<fieldname>() method(in this case it's clean_total_cost ) for the form, here's the doc . 您应该为clean_<fieldname>()使用clean_<fieldname>()方法(在本例中为clean_total_cost ),这是doc

from django import forms

class QuoteForm(forms.ModelForm):
    def clean_total_cost(self):
        total_cost = self.cleaned_data['total_cost']
        if total_cost <= 0:
            raise forms.ValidationError("Your value is less than zero")

        return total_cost

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM