Django

Insert Records into the Database using Django Shell or Admin Panel

๐Ÿ“Œ Introduction

After creating a model and applying migrations, the next step is to insert records into the database.

In Django, records can be inserted in multiple ways, but the two most common beginner-friendly methods are:

  • Django shell
  • Django admin panel

In this program, we will use the Student model created in the previous post and insert records into its database table.


๐ŸŽฏ Program Statement

๐Ÿ‘‰ Insert records into the database using Django shell or admin panel.


๐Ÿง  Prerequisite

This program assumes that the following model already exists from Post 43.

๐Ÿ“ File: models.py

๐Ÿ”น Path:

myproject/myapp/models.py

๐Ÿ”น Code:

from django.db import models

class Student(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
course = models.CharField(max_length=100)
email = models.EmailField(unique=True)

def __str__(self):
return self.name

โœ… Method 1: Insert Records using Django Shell


โš™๏ธ Step 1: Open Django Shell

Run:

python manage.py shell

โš™๏ธ Step 2: Import the Model

Type the following inside the shell:

from myapp.models import Student

โš™๏ธ Step 3: Create and Save a Record

Method A: Create object first, then save

s1 = Student(name="Charlie", age=21, course="MCA", email="charlie@gmail.com")
s1.save()

Method B: Direct create

Student.objects.create(name="Aman", age=22, course="BCA", email="aman@example.com")

โš™๏ธ Step 4: View All Inserted Records

Student.objects.all()

Example Output:

<QuerySet [<Student: Charlie>, <Student: Aman>]>

๐Ÿง  Explanation

  • Student(...) creates a model object
  • .save() stores it in the database
  • objects.create() both creates and saves the record in one line
  • objects.all() fetches all records

โœ… Method 2: Insert Records using Django Admin Panel

To insert records using admin, we first need to register the model.


โš™๏ธ Step 1: Register the Model in Admin

๐Ÿ“ File: admin.py

๐Ÿ”น Path:

myproject/myapp/admin.py

๐Ÿ”น Code:

from django.contrib import admin
from .models import Student

admin.site.register(Student)

๐Ÿง  Explanation

This line tells Django admin to display the Student model in the admin panel.


โš™๏ธ Step 2: Create Superuser

Run:

python manage.py createsuperuser

Example:

Username: admin
Email address: admin@example.com
Password: ********

โš™๏ธ Step 3: Run Server

python manage.py runserver

โš™๏ธ Step 4: Open Admin Panel

Open:

๐Ÿ‘‰ http://127.0.0.1:8000/admin/

Login using the superuser credentials.


โš™๏ธ Step 5: Add Student Record

After login:

  • Click Students
  • Click Add Student
  • Enter values like:
  • Click Save

๐Ÿง  Explanation

Django admin provides a ready-made interface for adding, editing, and deleting model records.

This is one of the biggest advantages of Django.


๐ŸŒ Result / Output

After inserting records, the Student table contains entries such as:

IDNameAgeCourseEmail
1Charlie21MCAcharlie@gmail.com
2Aman22BCAaman@example.com
3Riya21MCAriya@example.com

๐Ÿง  How It Works

Using Shell

  1. Open Django shell
  2. Import model
  3. Create object
  4. Save object to database

Using Admin

  1. Register model in admin.py
  2. Create superuser
  3. Login to admin panel
  4. Add records using GUI

๐Ÿ”ฅ Key Concepts

Import Model in Shell

from myapp.models import Student

Used to access model inside shell.


Save Record

s1.save()

Stores object in database.


Direct Insert

Student.objects.create(...)

Creates and saves in one line.


Admin Registration

admin.site.register(Student)

Makes model visible in admin panel.


Create Superuser

python manage.py createsuperuser

Creates admin login account.


โš ๏ธ Common Errors

โŒ Model not registered in admin

If you forget to add:

admin.site.register(Student)

the model will not appear in admin panel.


โŒ Superuser not created

You cannot access admin features without a superuser.


โŒ Duplicate email error

Since email has unique=True, Django will not allow duplicate email values.

Example invalid insertion:

Student.objects.create(name="Test", age=20, course="MCA", email="charlie@gmail.com")

This may raise a uniqueness error if the email already exists.


โŒ Forgot to import model in shell

Always import the model before using it:

from myapp.models import Student

โŒ Not saving object

If you create an object like this:

s1 = Student(name="Nyra", age=20, course="MCA", email="nyra@example.com")

but do not call:

s1.save()

the record will not be stored in the database.


๐Ÿงช Practice Questions

  1. Insert three more student records using shell
  2. Insert records using only admin panel
  3. Try inserting a duplicate email and observe the error
  4. Add one more field in model and insert a record again
  5. Display all records in shell using Student.objects.all()

๐ŸŽค Viva Questions & Answers

1. What is Django shell?

Django shell is an interactive Python environment connected to the Django project. It allows us to test models and database operations directly.

2. Why do we import the model in Django shell?

We import the model so that we can create, save, update, or query its records from the shell.

3. What is the use of .save() method?

The .save() method stores the created object into the database table.

4. What is objects.create() in Django?

objects.create() is a shortcut method that creates and saves a record in one step.

5. What is Django admin panel?

Django admin panel is a built-in management interface that allows us to manage model data using a web browser.

6. Why do we register a model in admin.py?

We register the model so that it appears in the admin panel and can be managed from there.

7. What is a superuser in Django?

A superuser is an administrator account that has full access to the Django admin panel.

8. What is the difference between shell insertion and admin insertion?

Shell insertion is code-based and useful for testing, while admin insertion is GUI-based and easier for manual data entry.

9. What happens if we insert a duplicate value in a unique field?

Django raises an error because unique fields do not allow duplicate values.


๐Ÿ‘‰ Next Post: Fetch Model Data and Display it Dynamically in Templates
๐Ÿ‘‰ Back to List: Django Programs (60 Questions with Solutions)


Further Reading

Introduction to Django Framework and its Features

Django Practice Exercise

Examples of Array Functions in PHP

Basic Programs in PHP

Registration Form Using PDO in PHP

Inserting Information from Multiple CheckBox Selection in a Database Table in PHP

programmingempire

princites.com

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *