Django TextField max_length validation for ModelForm

As of Django 1.2 this can be done by validators at model level, as explained here: https://docs.djangoproject.com/en/stable/ref/validators/ from django.core.validators import MaxLengthValidator class Comment(models.Model): comment = models.TextField(validators=[MaxLengthValidator(200)]) Since Django 1.7, you can use max_length which is only enforced in client side. See here

Django unique_together with nullable ForeignKey

Django 2.2 added a new constraints API which makes addressing this case much easier within the database. You will need two constraints: The existing tuple constraint; and The remaining keys minus the nullable key, with a condition If you have multiple nullable fields, I guess you will need to handle the permutations. Here’s an example … Read more

Custom form validation

To validate a single field on it’s own you can use a clean_FIELDNAME() method in your form, so for email: def clean_email(self): email = self.cleaned_data[’email’] if User.objects.filter(email=email).exists(): raise ValidationError(“Email already exists”) return email then for co-dependant fields that rely on each other, you can overwrite the forms clean() method which is run after all the … Read more

Custom validation in Django admin

Usually you just want to define a clean() method on the model itself. https://docs.djangoproject.com/en/2.1/ref/models/instances/#validating-objects from django.core.exceptions import ValidationError class Lecture(models.Model): topic = models.CharField(max_length=100) speaker = models.CharField(max_length=100) start_date = models.DateField() end_date = models.DateField() def clean(self): if self.start_date > self.end_date:: raise ValidationError(“Dates are incorrect”) Something like that will work in the django admin without any need to … Read more

What’s the best way to store a phone number in Django models?

You might actually look into the internationally standardized format E.164, recommended by Twilio for example (who have a service and an API for sending SMS or phone-calls via REST requests). This is likely to be the most universal way to store phone numbers, in particular if you have international numbers work with. Phone by PhoneNumberField … Read more

How to limit the maximum value of a numeric field in a Django model?

You can use Django’s built-in validators— from django.db.models import IntegerField, Model from django.core.validators import MaxValueValidator, MinValueValidator class CoolModelBro(Model): limited_integer_field = IntegerField( default=1, validators=[ MaxValueValidator(100), MinValueValidator(1) ] ) Edit: When working directly with the model, make sure to call the model full_clean method before saving the model in order to trigger the validators. This is not … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)