How to Extract and Import file in Django
Last Updated :
18 Mar, 2024
In Django, extracting and importing files is a common requirement for various applications. Whether it's handling user-uploaded files, importing data from external sources, or processing files within your application, Django provides robust tools and libraries to facilitate these tasks. This article explores techniques and best practices for extracting and importing files in Django, helping developers efficiently manage and utilize file-based data within their projects.
Extracting and Importing Files in Django
To install Django follow these steps.
Starting the Project Folder
To start the project use this command
django-admin startproject rest_tut
cd rest_tut
To start the app use this command
python manage.py startapp home
File Structure
File Structure
Register the app name in settings.py file. follow the Below commands
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"home", //App name
]
Creating necessary files
models.py: Here we are creating the models .The main function of models is to make connection with the database so that information can be stored in the database.
Python
from django.db import models
class GFG(models.Model):
name = models.CharField(max_length=100)
contact = models.CharField(max_length=100)
address = models.CharField(max_length=500)
class File(models.Model):
file = models.FileField(upload_to="excel")
views.py: Below is the explaination of the functions
- export_data_to_excel(request): This view is responsible for exporting data from the database to an Excel file.It retrieves all Employee objects from the database using Employee.objects.all().It creates an empty list called data.Finally, it returns a JSON response with a status code indicating a successful export (status 200).
- import_data_to_db(request): This view handles the import of data from an uploaded Excel file into the database.It initializes data_to_display as None, which will be used to display imported data on the web page.Finally, it renders the 'excel.html' template, passing the data_to_display variable in the context so that the imported data can be displayed on the webpage.
Python
from django.shortcuts import render
from .models import *
import pandas as pd
from django.http import JsonResponse
from django.conf import settings
def export_data_to_excel(request):
# Retrieve all Employee objects from the database
objs = GFG.objects.all()
data = []
for obj in objs:
data.append({
"name": obj.name,
"contact": obj.contact,
"address": obj.address
})
pd.DataFrame(data).to_excel('output.xlsx')
return JsonResponse({
'status': 200
})
def import_data_to_db(request):
data_to_display = None
if request.method == 'POST':
file = request.FILES['files']
obj = File.objects.create(
file=file
)
path = file.file
df = pd.read_excel(path)
data_to_display = df.to_html()
return render(request, 'excel.html', {'data_to_display': data_to_display})
Creating GUI
excel.html:This HTML file is used to upload file from the user to the database.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Excel</title>
<style>
h1 {
color: green;
font-size: 25px;
font-weight: bold;
}
</style>
</head>
<body>
<h1>GeeksforGeeks</h1>
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
<h4>Select & Upload File</h4>
<input type="file" required name="files">
<button type="submit">Submit</button>
</form>
{% if data_to_display %}
<div>
<h2>Uploaded Data</h2>
{{ data_to_display | safe }}
</div>
{% endif %}
</body>
</html>
admin.py: Here we are registering the models.
Python3
from django.contrib import admin
from home.models import *
admin.site.register(GFG)
urls.py :Here we are defining all the path of the project.
Python3
from django.contrib import admin
from django.urls import path
from home.views import *
urlpatterns = [
path('export_data_to_excel/', export_data_to_excel),
path('import_data_to_db/', import_data_to_db),
path("admin/", admin.site.urls),
]
Deployement 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
Chose File
Upload the data and click on Submit button
Conclusion:
In Django, the process of extracting and importing files plays a crucial role in developing data-driven web applications. It allows users to upload files, such as Excel spreadsheets or CSV files, which are then processed to extract valuable information. This data can be stored in a structured manner within a database, facilitating easy retrieval and analysis. Django's security measures ensure the safe handling of files and user data during the upload and import process, making it a fundamental feature for building robust and user-friendly web applications with seamless data integration you can downalod the output.xlxs file by click here download
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read