Open In App

How to Clone and Save a Django Model Instance to the Database

Last Updated : 08 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In the realm of web development, Django stands out as a robust and versatile framework for building web applications swiftly and efficiently. One common requirement in Django projects is the ability to clone or duplicate existing model instances and save them to the database. This functionality is particularly useful when dealing with repetitive data entry tasks or when creating variations of existing records without starting from scratch.

This article will guide you through the process of cloning a Django model instance object and saving it to the database. We'll walk through the steps with a small web project to demonstrate this process clearly.

How to Clone a Django Model Instance Object and Save It to the Database?

Setting Up the Django Project

Before diving into cloning model instances, let's set up a basic Django project if you haven't already:

Install Django: If Django isn't installed, you can install it using pip:

pip install django

Create a Django Project: Start a new Django project using:

django-admin startproject clone_project

Create an App: Inside the project directory, create a new Django app:

cd clone_project
python manage.py startapp clones

Updates settings.py

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'clones',
]

File Structure

fff

Configure Models: Define your models in clones/models.py. For demonstration, let's create a simple model:

Python
# clones/models.py
from django.db import models

class Product(models.Model):
    name = models.CharField(max_length=100)
    price = models.DecimalField(max_digits=8, decimal_places=2)

    def __str__(self):
        return self.name

Create Views: Define views in clones/views.py. For example:

Python
# clones/views.py
from django.shortcuts import render, redirect, get_object_or_404
from .models import Product

def product_list(request):
    products = Product.objects.all()
    return render(request, 'product_list.html', {'products': products})

def clone_product(request, product_id):
    original_product = get_object_or_404(Product, pk=product_id)
    cloned_product = Product(
        name=f"Clone of {original_product.name}",
        price=original_product.price
    )
    cloned_product.save()
    return redirect('product_list')

Configure URLs: Configure URLs in clones/urls.py:

Python
# clones/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('', views.product_list, name='product_list'),
    path('clone/<int:product_id>/', views.clone_product, name='clone_product'),
]

clone_project/urls.py

Python
from django.contrib import admin
from django.urls import path, include
from clones.views import *

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('clones.urls')),
]

Create Templates: Create templates in clones/templates/ directory product_list.html.

HTML
<!-- clones/templates/product_list.html -->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Product List</title>
</head>
<body>
    <h1>Product List</h1>
    
    <ul>
        {% for product in products %}
            <li>{{ product.name }} - ${{ product.price }}</li>
            <a href="{% url 'clone_product' product_id=product.id %}">Clone</a>
        {% empty %}
            <li>No products found.</li>
        {% endfor %}
    </ul>
</body>
</html>

Migrate Database

Apply migrations to create the database schema:

python manage.py makemigrations
python manage.py migrate

Createsuperuser

python manage.py createsuperuser

Run the Development Server:

Start the Django development server:

python manage.py runserver

Access the Application:

Open a web browser and go to http://127.0.0.1:8000/ to see your product list. You can click on the "Clone" link next to each product to clone it.



Next Article
Practice Tags :

Similar Reads