Open In App

How to Import a JSON File to a Django Model?

In many web development projects, it's common to encounter the need to import data from external sources into a Django application's database. This could be data obtained from APIs, CSV files, or in this case, JSON files. JSON (JavaScript Object Notation) is a popular format for structuring data, and integrating it into a Django project can be quite beneficial.

Importing JSON Data into Models in Django

In this project, we'll explore how to import JSON data into a Django database using a Python script. We'll create a Django application, define a model to represent our data, write a Python code to parse the JSON file and save it into the database, and execute the code to import the data.

Starting the Project Folder

To start the project use this command:

django-admin startproject json_import_project
cd json_import_project

To start the app use this command

python manage.py startapp book

Now add this app to the ‘settings.py’

INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"book",
]

json file (script.json)

[
{
"title": "To Kill a Mockingbird",
"author": "Harper Lee",
"publication_year": 1960
},
{
"title": "The Great Gatsby",
"author": "F. Scott Fitzgerald",
"publication_year": 1925
}
]

File Structure

jjj

Setting Necessary Files

models.py :Below code defines a Django model named "Book" with three fields: "title" (a character field with a maximum length of 100 characters), "author" (also a character field), and "publication_year" (an integer field).

# In book/models.py
from django.db import models


class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=100)
    publication_year = models.IntegerField()

views.py :Below, code defines a view function named "import_data" that handles POST requests. It checks if a JSON file is uploaded, reads its content, iterates over each item in the data, creates a new Book object for each item, and saves it to the database.

# In book/views.py
from django.shortcuts import render
from .models import Book
import json


def import_data(request):
    if request.method == 'POST' and request.FILES['json_file']:
        json_file = request.FILES['json_file']
        data = json.load(json_file)
        for item in data:
            book = Book(
                title=item['title'],
                author=item['author'],
                publication_year=item['publication_year']
            )
            book.save()
        return render(request, 'success.html')
    return render(request, 'form.html')

Creating GUI

form.html: Below, HTML code defines a form page titled "Import JSON Data". It contains a form with a file input field where users can upload a JSON file. Upon submission, the form sends a POST request with the uploaded file to the server for processing.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Import JSON Data</title>
</head>
<body>
    <h1>Import JSON Data</h1>
    <form method="post" enctype="multipart/form-data">
        {% csrf_token %}
        <input type="file" name="json_file">
        <button type="submit">Import</button>
    </form>
</body>
</html>

success.html : HTML code defines a page titled "Import Successful". It notifies users that the JSON data has been successfully imported into the database. Additionally, it provides a link for users to navigate back to the import page.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Import Successful</title>
</head>
<body>
    <h1>Import Successful!</h1>
    <p>The JSON data has been successfully imported into the database.</p>
    <a href="/">Go back to import page</a>
</body>
</html>

urls.py: Below, is the urls.py file connect HTML with views.py file.

from django.contrib import admin
from django.urls import path
from book.views import *

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

admin.py: Here, we registered our model.

from django.contrib import admin
from book.models import *

# Register your models here.
admin.site.register(Book)

Deployment of the Project

Run these commands to apply the migrations:

python3 manage.py makemigrations
python3 manage.py migrate

Run the server with the help of following command:

python3 manage.py runserver

Output

kkk

Video Demonstration

Article Tags :