In Django, the CharField
is a field type used to store short to medium-length strings, such as names, titles, and other text data. It's one of the most commonly used field types for text-based data in Django models.
Parameters and Attributes:
-
max_length (required): This parameter specifies the maximum number of characters allowed in the field. It is a required parameter for
CharField
. For example,max_length=50
limits the field to 50 characters. -
blank: A boolean parameter that, when set to
True
, allows the field to be left blank (i.e., it's not required). The default isFalse
. It is useful while creating Forms. -
null: A boolean parameter that, when set to
True
, allows the field to have aNULL
database value. The default isFalse
. -
default: This parameter allows you to set a default value for the field. For example,
default='Default Value'
sets the default value to 'Default Value'. -
choices: You can specify a list of choices using the
choices
parameter, which restricts the allowed values to a predefined set. -
unique: You can also specify a column to take only unique values. If a field is set to unique, then it will show an error when the duplicate values are tried to be inserted in that field. The default is
False
. More details about the unique parameter can be viewed here. -
validators: You can add custom validation functions using the
validators
parameter to ensure that the data in the field meets specific criteria.
A model example can be as follows :
class Person(models.Model):
GENDER_CHOICES = (
('M', 'Male'),
('F', 'Female'),
)
first_name = models.CharField(max_length=30)
bio = models.CharField(max_length=500, blank=True, null=True)
gender = models.CharField(max_length=1, choices=GENDER_CHOICES, default="M")
Here,
- first_name is a Char Field with a maximum lenght of 30.
- bio is given a Char Field with blank=True and null=True, which means if the field is not given while creating an object it won't cause any error.
- The gender has a set of choices that allows only two values in it, and if it is not provided it will take the default value as M.
You need to run the python manage.py makemigrations
and python manage.py migrate
commands to create the model.
python manage.py makemigrations
python manage.py migrate
You can create objects for the model as follows :
from datatypedemo.models import Person
p=Person.objects.create(first_name='EDKOOL')
vars(p)
Here, since no value has been given for the gender its taken as M by default. Also the bio is None as it has not been specified.
You can add bio and change the value of gender as well for the object.
p.bio="This is Edkool's bio"
p.gender='F'
p.save()
As the values of bio and gender has changed there are updated correspondingly.
Furthermore, you can add validations for particular fields, say you want to add a validation that if the bio field is present, it should containt at least 50 characters, you can add it as follows :
def validate_bio(value):
if value and len(value)<50:
raise ValidationError(f"Length of Bio is {len(value)}. It should be atleast 50 characters")
class Person(models.Model):
GENDER_CHOICES = (
('M', 'Male'),
('F', 'Female'),
)
first_name = models.CharField(max_length=30)
bio = models.CharField(max_length=500, validators=[validate_bio],blank=True, null=True)
gender = models.CharField(max_length=1, choices=GENDER_CHOICES,default="M")
You need to run python manage.py makemigrations
and python manage.py migrate
in order to incorporate the changes.
python manage.py makemigrations
python manage.py migrate
Now, if you check the object that was created, it will show a validation error.
from datatypedemo.models import Person
p=Person.objects.get(id=1)
p.full_clean()
The error is as follows :
raise ValidationError(errors)
django.core.exceptions.ValidationError: {'bio': ['Length of Bio is 20. It should be atleast 50 characters']}
If you try to assign the bio to None or put more than 50 characters then the validation error will go away.
p.bio=None
p.save()
p.full_clean()
As you can see, no error has been displayed as the bio is set to None.
The CharField
in Django is highly versatile and customizable, making it a suitable choice for storing various text-based data in your models. It's important to choose an appropriate max_length
value based on your data requirements to ensure data integrity in the database.