0
0
Djangoframework~5 mins

Field options (max_length, null, blank, default) in Django

Choose your learning style9 modes available
Introduction

Field options help control how data is stored and validated in your database. They make sure your data fits rules you set, like length limits or default values.

When you want to limit the number of characters a text field can hold.
When you want to allow a database field to be empty or have no value.
When you want to allow a form field to be left blank by the user.
When you want to set a default value for a field if none is provided.
Syntax
Django
field_name = models.CharField(max_length=100, null=True, blank=True, default='example')

max_length sets the maximum number of characters for text fields.

null=True means the database can store a NULL value for this field.

blank=True means the field can be left empty in forms.

default sets a value automatically if none is given.

Examples
This field requires text up to 50 characters. It cannot be empty or null.
Django
name = models.CharField(max_length=50)
This field can be empty in forms and store NULL in the database.
Django
description = models.TextField(null=True, blank=True)
This field defaults to 'pending' if no value is given.
Django
status = models.CharField(max_length=20, default='pending')
Sample Program

This model defines a product with a name, optional description, and a status that defaults to 'available'. When creating a product without description or status, description is None and status is 'available'.

Django
from django.db import models

class Product(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField(null=True, blank=True)
    status = models.CharField(max_length=20, default='available')

# Example usage:
product = Product(name='Coffee Mug')
print(product.name)          # Coffee Mug
print(product.description)   # None
print(product.status)        # available
OutputSuccess
Important Notes

Use null=True only for non-string fields or when you want to store NULL in the database.

blank=True affects form validation, allowing empty input.

Always set max_length for CharField to avoid errors.

Summary

max_length limits text size.

null controls database NULL values.

blank controls form input allowance.

default sets a fallback value.