Reputation: 778
The Django docs indicate that:
The max_length is enforced at the database level and in Django’s validation.
What, exactly does this mean? I have a routine to parse an input CSV file to create some models, and an over-length Name
field got in there along the way as I created objects using:
new_standard = Standard.objects.create(Name=lname,ShortName=sname,calcmethod=method,Description=descr,course=course,Order=stdnum)
new_standard.save()
The error was only raised later, as the user tried to edit the object using a form (which wouldn't validate). When using the same form to create objects, the input field won't allow typing past the 30th character, but my manual method seems to allow the over-length field to be created.
How do I avoid this (apart from manually truncating strings after checking field lengths, which I could do, but which seems like a lot of hassle - seems like I could handle it in the form or DB)? Now that I have some of these time bombs in my DB, what's the easiest way to get rid of them?
Upvotes: 1
Views: 1057
Reputation: 308879
For historic reasons, Django validation is not called when you create or save an object, but it is triggered by model forms, including in the Django admin.
You could manually trigger validation by calling full_clean()
from django.core.exceptions import ValidationError
new_standard = Standard(Name=lname,ShortName=sname,calcmethod=method,Description=descr,course=course,Order=stdnum)
try:
new_standard.full_clean()
except ValidationError as exp:
# Do something here
pass
else:
save()
Note that max_length
is not enforced by SQLite. If you were using a different database, you would get an integrity error when you tried to save a string that was too long.
Upvotes: 2