Lesson 31 of 60 – Creating Records in Django
52%

Creating Records in Django

In Django, you can create database records using the Django ORM. Instead of writing SQL INSERT statements manually, Django provides Python methods such as create() and save() to insert records into a database.

Note: Before creating records, make sure your model has been created, migrations have been applied, and the Django app is added to INSTALLED_APPS.

1. What is a Database Record?

A database record is a single row of data stored in a database table. For example, a Student table may contain information such as name, email, age, and course.

Name: Rahul
Email: rahul@example.com
Age: 20
Course: Python

In Django, each record is usually represented by an instance of a model.

2. Creating Records with Django ORM

Django ORM allows you to create database records using Python code.

Student.objects.create(
    name="Rahul",
    age=20
)

Django converts this operation into the appropriate database INSERT operation.

3. Example Student Model

Consider the following model:

from django.db import models

class Student(models.Model):

    name = models.CharField(max_length=100)

    email = models.EmailField()

    age = models.IntegerField()

    course = models.CharField(max_length=100)

This model can be used to create Student records.

4. Using create()

The create() method is one of the easiest ways to create a new database record.

student = Student.objects.create(
    name="Rahul",
    email="rahul@example.com",
    age=20,
    course="Python"
)

The record is created and saved to the database immediately.

5. Creating a Record with save()

Another approach is to create a model object first and then call save().

student = Student(
    name="Rahul",
    email="rahul@example.com",
    age=20,
    course="Python"
)

student.save()

The save() method writes the object to the database.

6. create() vs save()

Both methods can create database records, but their usage is slightly different.

  • create() creates and saves the object in one operation.
  • save() allows you to create and modify the object before saving.
Student.objects.create(
    name="Amit",
    age=21
)
student = Student(
    name="Amit",
    age=21
)

student.save()

7. Importing the Model

Before using a model in another Python file, import it.

from .models import Student

For example, inside views.py:

from django.shortcuts import render
from .models import Student

8. Creating a Record in views.py

A record can be created inside a Django view.

from django.http import HttpResponse
from .models import Student

def create_student(request):

    Student.objects.create(
        name="Rahul",
        email="rahul@example.com",
        age=20,
        course="Python"
    )

    return HttpResponse(
        "Student created successfully"
    )

9. Saving Data with Variables

You can store values in Python variables and use them while creating a record.

student_name = "Amit"
student_age = 21

Student.objects.create(
    name=student_name,
    age=student_age
)

This is useful when data comes from a form, API, or another source.

10. Creating a Record with Default Values

If a model field has a default value, you do not have to provide that value when creating the record.

class Student(models.Model):

    name = models.CharField(max_length=100)

    is_active = models.BooleanField(
        default=True
    )

Now you can create a student without explicitly providing is_active.

Student.objects.create(
    name="Rahul"
)

11. Creating Records with Dates

Django models can contain date fields.

from django.utils import timezone

student = Student.objects.create(
    name="Rahul",
    admission_date=timezone.now()
)

Django provides useful utilities for working with dates and times.

12. Auto Date Fields

Django can automatically store the creation date of a record using auto_now_add=True.

created_at = models.DateTimeField(
    auto_now_add=True
)

When a new record is created, Django automatically sets the creation time.

13. Creating Multiple Records

You can create multiple objects in Python and save them individually.

student1 = Student(
    name="Rahul",
    age=20
)

student2 = Student(
    name="Amit",
    age=21
)

student1.save()
student2.save()

Each object is stored as a separate database record.

14. bulk_create()

Django also provides bulk_create() for creating multiple objects efficiently.

students = [
    Student(name="Rahul", age=20),
    Student(name="Amit", age=21),
    Student(name="Priya", age=19)
]

Student.objects.bulk_create(students)

This is useful when inserting many records at once.

15. Creating Records from a Form

In real applications, users commonly enter information through an HTML form. The submitted data can then be used to create a model record.

name = request.POST.get("name")
email = request.POST.get("email")

Student.objects.create(
    name=name,
    email=email
)

For proper form handling and validation, Django Forms or ModelForms are usually preferred.

16. Checking Request Method

When processing an HTML form, you can check whether the request uses POST.

def create_student(request):

    if request.method == "POST":

        name = request.POST.get("name")

        Student.objects.create(
            name=name
        )

        return HttpResponse(
            "Student created"
        )

17. Simple HTML Form

A simple HTML form can collect student information.

<form method="POST">

    {% csrf_token %}

    <input
        type="text"
        name="name"
        placeholder="Student Name"
    >

    <input
        type="email"
        name="email"
        placeholder="Email"
    >

    <button type="submit">
        Save
    </button>

</form>

The submitted data can be processed by a Django view.

18. Why Use csrf_token?

Django provides CSRF protection for POST forms.

{% csrf_token %}

The CSRF token should normally be included inside Django forms that submit POST requests.

Important: Do not remove CSRF protection just to make a form work. Handle CSRF errors correctly.

19. Validating Data Before Saving

User input should be validated before creating database records.

name = request.POST.get("name")

if name:

    Student.objects.create(
        name=name
    )

Django Forms and ModelForms provide more structured validation for larger applications.

20. Handling Unique Fields

A model field can be configured with unique=True.

email = models.EmailField(
    unique=True
)

This prevents duplicate values for that field at the database level.

Student.objects.create(
    name="Rahul",
    email="rahul@example.com"
)

21. Handling Integrity Errors

Creating a record can fail when database constraints are violated. For example, a unique field may already contain the submitted value.

from django.db import IntegrityError

try:

    Student.objects.create(
        name="Rahul",
        email="rahul@example.com"
    )

except IntegrityError:

    print("Could not create record")

In production applications, errors should be handled appropriately for the specific application.

22. Creating Records with ForeignKey

A model can contain a ForeignKey to another model.

class Course(models.Model):

    name = models.CharField(
        max_length=100
    )


class Student(models.Model):

    name = models.CharField(
        max_length=100
    )

    course = models.ForeignKey(
        Course,
        on_delete=models.CASCADE
    )

You can create a student using an existing course object.

Student.objects.create(
    name="Rahul",
    course=course
)

23. Creating Records with get_or_create()

The get_or_create() method attempts to find an existing object. If it does not exist, Django creates one.

student, created = Student.objects.get_or_create(
    email="rahul@example.com",
    defaults={
        "name": "Rahul",
        "age": 20
    }
)

The created value tells you whether a new record was created.

24. Checking Whether a Record Was Created

With get_or_create(), the returned boolean indicates whether the object was newly created.

student, created = Student.objects.get_or_create(
    email="rahul@example.com",
    defaults={
        "name": "Rahul"
    }
)

if created:
    print("New student created")
else:
    print("Student already exists")

25. Creating Records in Django Shell

You can test record creation using the Django shell.

python manage.py shell

Then import the model:

from students.models import Student

Create a record:

Student.objects.create(
    name="Rahul",
    age=20
)

26. Checking the Created Record

After creating a record, you can store the returned object and inspect it.

student = Student.objects.create(
    name="Rahul",
    age=20
)

print(student.id)
print(student.name)
print(student.age)

If the model uses an automatically generated primary key, Django assigns the ID when the record is saved.

27. Creating a Record and Redirecting

After successfully processing a form, a view can redirect the user to another page.

from django.shortcuts import redirect

def create_student(request):

    if request.method == "POST":

        Student.objects.create(
            name=request.POST.get("name")
        )

        return redirect("student_list")

Redirecting after a successful POST is commonly used to avoid accidental duplicate form submissions when a page is refreshed.

28. Complete Create View Example

from django.shortcuts import redirect
from django.http import HttpResponse
from .models import Student

def create_student(request):

    if request.method == "POST":

        name = request.POST.get("name")
        email = request.POST.get("email")
        age = request.POST.get("age")

        if name and email and age:

            Student.objects.create(
                name=name,
                email=email,
                age=age
            )

            return HttpResponse(
                "Student created successfully"
            )

        return HttpResponse(
            "Please enter all required fields"
        )

    return HttpResponse(
        "Submit the student form"
    )

29. Common Mistakes While Creating Records

  • Forgetting to import the model.
  • Using a field name that does not exist in the model.
  • Forgetting to run migrations after changing models.
  • Not validating user input.
  • Ignoring unique-field constraints.
  • Forgetting {% csrf_token %} in POST forms.
  • Using get() when multiple records may match.
  • Creating duplicate records without checking the application's requirements.
  • Not handling database errors appropriately.

30. Summary of Creating Records

Django provides several useful ORM methods for creating database records.

  • objects.create() creates and saves a record.
  • Model(...) creates an unsaved model object.
  • save() saves a model object to the database.
  • bulk_create() creates multiple records efficiently.
  • get_or_create() retrieves or creates a record.
  • Forms and ModelForms can be used to validate user input.
  • POST requests are commonly used when submitting new data.
  • CSRF protection should be maintained for POST forms.
  • Database constraints should be considered when creating records.
  • Django ORM reduces the need to write SQL INSERT statements manually.

📌 Key Points

  • Django ORM allows records to be created using Python.
  • objects.create() is a simple way to create and save a record.
  • save() can be used after creating a model instance.
  • bulk_create() is useful for multiple records.
  • get_or_create() can find or create a record.
  • User input should be validated before saving it.
  • Django Forms and ModelForms provide structured validation.
  • POST forms should include CSRF protection.
  • Database constraints such as unique fields should be handled carefully.
  • Records can be created from views, forms, or the Django shell.

🧠 Quick Quiz

Question: Which Django ORM method creates and saves a new database record in one operation?