Django Single Field Validation cleaned_data

82 Views Asked by At

I am new in django and I am learning validation topics. Now I have a question about Single Field Validation and cleaned_data dictionary.I run django 3.2. In my model.py there is this table:

class Personen(models.Model):
    DEUTSCHLAND = 'DE'
    SCHWEIZ = "CH"
    ÖSTERREICH = "AT"
    ENGLAND = "UK"
    NATION_CHOICES = [
        (DEUTSCHLAND, "Deutschland"),
        (SCHWEIZ, "Schweiz"),
        (ÖSTERREICH, "Österreich"),
        (ENGLAND, "England"),
    ]
    vorname = models.CharField(max_length=200)
    nachname = models.CharField(max_length=200)
    username = models.CharField(max_length=200)
    stadt = models.CharField(max_length=15, validators=[
                             validate_nation_regexval], null=True)
    nationalität = models.CharField(
        max_length=2, choices=NATION_CHOICES, default=DEUTSCHLAND)
    biere = models.ManyToManyField("Bier", through="PersonenBier")

    def __str__(self):
        return self.username

I import this in forms.py and I want to validate the field 'username'. So I created a single field validation in forms.py


class PersonenForm(ModelForm):
    class Meta:
        model = Personen
        fields = '__all__'

    def clean_username(self):
        print(self.cleaned_data)
        username_passed = self.cleaned_data["username"]
        username_req = "user_"
        if not username_req in username_passed:
            raise ValidationError("Ungültig")
        return username_passed

So far everything works, but I am confused, as I expected, that the cleaned_data dict only includes the 'username' field. Why are there are also the 'vorname' and 'nachname' keys in the dict?

console output cleaned_data dict

1

There are 1 best solutions below

1
On

cleaned_data calls the clean() method so it contains all the validated fields.

An excerpt from the docs:

The clean_() method is called on a form subclass – where is replaced with the name of the form field attribute. This method does any cleaning that is specific to that particular attribute, unrelated to the type of field that it is. This method is not passed any parameters. You will need to look up the value of the field in self.cleaned_data and remember that it will be a Python object at this point, not the original string submitted in the form (it will be in cleaned_data because the general field clean() method, above, has already cleaned the data once).

you can read form validation steps in the above link I shared.