theamateurdataanalyst
theamateurdataanalyst

Reputation: 2834

Validate single field of ModelForm in Django

I am having trouble validating a single field in 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. The think the reason I am getting this errors is because I dont have forms.ModelForm as the first argument in my class. If I do this then I get the following error:

name 'forms' is not defined

Can anyone help?

Upvotes: 1

Views: 3286

Answers (1)

Shang Wang
Shang Wang

Reputation: 25539

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.

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

Upvotes: 3

Related Questions