How Can Upload Files/Images using Django Form

# Create your views here.

def html_view(request):

   if request.method == 'GET':

       return render(request, "form.html")

dd = request.FILES['image_url']

 dd2 = request.FILES['image_url2']

 dd3 = request.FILES['image_url3']

 dd4 = request.FILES['image_url4']

 images = [dd, dd2, dd3, dd4]

 for image in images:

   ProductImage.objects.create('product'=request.POST['product'], 'image_url': image)

return render(request, "form.html")

View More...

Django Python Command

Verify Python Installation


Check Python Version

>python --version

shortcut command

>python -V

>python3 -V

Check if PIP is Already Installed

>pip help

Installing PIP On Windows Machine

Download PIP

Copy PIP code and save file name is

PIP is a command-line program. When you install PIP, the PIP command is added to your system.


Check PIP Version

>pip --version

shortcut command

>pip -V

Upgrading PIP for Python on Windows Machine

>python -m pip install --upgrade pip

Downgrade PIP Version

>python -m pip install pip==18.1

Creating virtual environment for window Machine

>python -m virtualenv env

Activate virtual environment for window Machine


Create Virtual environment for ubuntu/linux machine

>python -m venv env

Activate virtual environment for ubuntu/linux machine

>source env/bin/activate

Deactivate virtual environment


Install django and mysqlclient sh > pip install django > pip install mysqlclient

Install Django

>python -m pip install django

shortcut command

>pip install django

If you wante to install Specific version of django

>pip install django==3.1.7

Check Django Version

>django-admin --version

Install mysqlclient for MYSQL Database

>pip install mysqlclient

if you got installation error in window 

 then download whl files from here

Download :

for window 32 bit

>pip install mysqlclient-1.4.6-cp38-cp38-win32.whl

for window 64 bit

>pip install mysqlclient-1.4.6-cp38-cp38-win_amd64.whl

Creating Django Project

>django-admin startproject demo_project

Creating Django APP

>django-admin startapp demo_app

Note: django-admin is equal to python command

i.e django-admin = python

>python startapp demo_app

Django Migration Command

>python makemigrations

>python migrate

Create Super User for Django admin

>python createsuperuser

Run Server for Django Project

>python runserver

Exporting data from a Django project

>python dumpdata > vishavjeet_data.json

If you want the exported file to have a readable JSON,

 then you can use "--indent".

>python dumpdata --indent=4 > dumped_data.json

Importing data from a Django project

>python loaddata < vishavjeet_data.json

View More...

Upload CSV file using Django

Djnago Project Setup for upload CSV file

Import CSV data into mysql database using django

# Step1: Installation or Setup

Creating virtual environment for window and activate

>python -m virtualenv env


Create Virtual environment for ubuntu/linux and activate

>python -m venv env

>source env/bin/activate

Install django and mysqlclient

> pip install django

> pip install mysqlclient

Creating Project and App

> django-admin startproject test_demo

> django-admin startapp dump_csv_import

#Step2: Change database connection in for mysql instead of default sqllite











#Step3: Create a model name DumpTender, which code given below

from django.db import models

import random

import string

from django.db.models.signals import pre_save

from django.utils.text import slugify

# Create your models here.


('Active', 'Active'),

('Deactive', 'Deactive')


def random_string_generator(size=10, chars=string.ascii_lowercase + string.digits):

rand_str = ''.join(random.choice(chars) for _ in range(size))

return rand_str

def unique_slug_generator(instance, new_slug):

if new_slug is not None:

slug = new_slug.replace(" ", "-")


slug = slugify(instance.product_title)

klass = instance.__class__

qs_exists = klass.objects.filter(product_slug=slug).exists()

if qs_exists:

rand_str = random_string_generator(4)

new_slug = f"{slug}-{rand_str}"

return unique_slug_generator(instance, new_slug)

return slug

class DumpTender(models.Model):

id = models.AutoField(primary_key=True, unique=True)

product_id = models.IntegerField()

product_sku = models.CharField(max_length=64)

product_title = models.CharField(max_length=128)

product_slug = models.SlugField(max_length=256, default='', null=True, blank=True)

product_price = models.FloatField(default=0.0)

quantity = models.IntegerField()

total_price = models.FloatField(default=0.0)

created_datetime = models.DateTimeField(auto_now_add=True)

updated_datetime = models.DateTimeField(auto_now=True)

status = models.CharField(max_length=32, default='Deactive', choices=STATUS)

def __str__(self):

return self.product_title

class Meta:

db_table = 'products'

ordering = ('-created_datetime',)

def dumptender_pre_save_receiver(sender, instance, *args, **kwargs):

if not instance.product_slug:

instance.product_slug = unique_slug_generator(instance, instance.product_title)

klass = instance.__class__

qs_exists = klass.objects.filter(product_slug=instance.product_slug).exists()

if qs_exists:

instance.product_slug = unique_slug_generator(instance, instance.product_title)

pre_save.connect(dumptender_pre_save_receiver, sender=DumpTender)

# Step4: Register our model in the file:

from django.contrib import admin

# Register your models here.

from dump_csv_import.models import DumpTender

# Step5: Let's migrate our model:

>python makemigrations

>python migrate

>python createsuperuser

# Step6: Now, let's write on our file to create a function-based view:

import csv

from datetime import datetime

import io

from django.contrib import messages

from django.shortcuts import render

# Create your views here.

from dump_csv_import.models import DumpTender

def dump_tender(request):

prompt = {

'order': 'Product of the CSV should be product_id, product_sku, product_title, product_slug,'

'product_price, quantity, total_price, created_datetime, updated_datetime, status',

'products': DumpTender.objects.all()


if request.method == "GET":

return render(request, "dump_tender.html", prompt)

if not request.FILES['file'].name.endswith('.csv'):

messages.error(request, 'THIS IS NOT A CSV FILE')

if request.FILES['file'].name.endswith('.csv'):

data_set = request.FILES['file'].read().decode('UTF-8')

io_string = io.StringIO(data_set)



for column in csv.reader(io_string, delimiter=',', quotechar="|"):


_created_at = datetime.strptime(column[6].replace('/','-'), "%m-%d-%Y %H:%M")

_updated_at = datetime.strptime(column[6].replace('/', '-'), "%m-%d-%Y %H:%M")

_, created = DumpTender.objects.update_or_create(







total_price=int(column[4]) * int(column[5]),





context = {

'messages': [f' {i} Products uploaded successfully'],

'products': DumpTender.objects.all()


return render(request, "dump_tender.html", context)

# Step7: Create a templates folder in the app dump_csv_import

 directory and a new HTML file named dump_tender.html (dump_csv_import/templates/dump_tender.html)

<!DOCTYPE html>

<html lang="en">


<title>Dump Tender</title>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<link rel="stylesheet" href="">

<script src=""></script>

<script src=""></script>



<div class="container">

<h2>Upload Dump Tender Products</h2>

<p>Only CSV File accept</p>

{% if messages %}

{% for message in messages %}

<!-- | means OR operator-->

<div class="alert alert-success alert-dismissible">

<a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>



{% endfor %}

{% else %}

<div class="alert alert-success alert-dismissible">

<a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>



<form class="form-inline" action="" method="POST" enctype="multipart/form-data">

{% csrf_token %}

<div class="form-group">

<label class="sr-only" for="file1">Upload a file:</label>

<input type="file" class="form-control" id="file1" name="file">


<button type="submit" class="btn btn-default">Upload</button>


{% endif %}

<h2>Products List</h2>

<table class="table">








<th>Total Price</th>

<th>Created Date</th>

<th>Updated Date</th>





{% for product in products %}


<td>{{ forloop.counter }} </td>










{% endfor %}






#Step8: Add Templates directory in




'DIRS': [os.path.join(BASE_DIR, "templates"), ],




#Step9: Create files in app directory and write code which are given below.

from django.urls import path

from dump_csv_import import views

urlpatterns = [

path('', views.dump_tender),


#Step10: include urls path in projcect's

from django.contrib import admin

from django.urls import path, include

urlpatterns = [


path('dump-tender', include('dump_csv_import.urls')),


# Step11: Now, create a new product_demo.csv file and try to upload it:

product_id, product_sku, product_title, product_slug, product_price, quantity, total_price, created_datetime, updated_datetime, status

View More...