django 2.0
I have a django model, with different slug fields:
from django.core.validators import validate_slug
class MyModel(models.Model):
# with slug field
slug_field = models.SlugField(max_length=200)
# or charfield with slug validator (should be exactly the same)
char_field = models.CharField(max_length=200, validators=[validate_slug])
The first problem i have, in my form i have a clean method, to validate the values of multiple fields, not individually. This method should theoretically be called after the clean_fields
method, but it is called even if clean_fields
raise an error.
My forms.py:
class MyForm(forms.ModelForm):
class Meta:
model = MyModel
fields = '__all__'
def clean(self):
cleaned_data = super().clean()
print(cleaned_data.get('slug_field')) # > None
print(cleaned_data.get('char_field')) # > ééé; uncleaned data
print(self.errors) # only from slug_field
return cleaned_data
With SlugField, slug_field
is not set in cleaned_data
, when it's invalid, and after the error is raised and returned to the user by the form. (I don't see why clean()
is even reached, because clean_fields()
have raised the error before)
The problem is that with the CharField
with any custom validator (validate_slug
or a self made one), the uncleaned value is returned in cleaned_data
. However, the validation error is still raised, but after.
This is quite dangerous for me, because i used to trust cleaned_data
, to modify data not saved inside the model.