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?
cleaned_data
calls theclean()
method so it contains all the validated fields.An excerpt from the docs:
you can read form validation steps in the above link I shared.