Skip to main content

How to upload a csv file in django?

csv file:--> It stands for comma separated value files.It is in the form of the tabular format and we can open it in Microsoft Excel.

Now see how we can upload it in the django..first we create a project in django.to create a project the commands are as follows:

         django-admin startproject csv
    $ cd csv
    $ python manage.py startapp csvfile

Once we have created an app we have to add this app in the INSTALLED_APPS  in settings.py.

In the models.py we have to created two class one is Bank and other is Branch.

from django.db import models


class Bank(models.Model):
    name = models.CharField(max_length=50)

    class Meta:
        ordering = ('name',)

    def __str__(self):
        return "{}".format(self.name)

class Branch(models.Model):
    name = models.CharField(max_length=256)  # branch 
    ifsc = models.CharField(max_length=500unique=True)
    bank = models.ForeignKey(Bank)
    address = models.TextField()
    city = models.CharField(max_length=500)
    district = models.CharField(max_length=500)
    state = models.CharField(max_length=500)

    class Meta:
        ordering = ('name',)
        verbose_name = 'Branch'
        verbose_name_plural = 'Branch'
    
    def __str__(self):
        return "{} - {} - {}".format(self.name, self.city, self.bank)
After creating these classed we have to migrate the model so that it can make a table in the database..
python manage.py makemigrations 
from this command there is file created in out migrations folder in our django projects which means that the migrations is save in our django project but till now do not create a table in our database..For that the command is 
python manage.py migrate    Now our migration is completed 


Register our model in the admin.py file:

from django.contrib import admin# Register your models here.
from .models import Bank,Branch
admin.site.register((Bank,Branch))

In the views the code is :


import csv
from rest_framework.response import Response
from django.contrib import messages
from django.shortcuts import render
from django.views import View
from .models import Bank, Branch

class ImportView(View):
    def get(selfrequest):
        return render(request, 'csv_fileupload.html')

    def post(selfrequest):
        csv_file = request.FILES.get('csv_file')
        decoded_file = csv_file.read().decode('utf-8').splitlines()
        reader = csv.DictReader(decoded_file)
        count = 0
        # ifsc_list = list(Branch.objects.values_list('ifsc', flat=True))
        for row in reader:
            bank_name = row.get('bank_name')
            ifsc = row.get('ifsc')
            branch = row.get('branch')
            address = row.get('address')
            city = row.get('city')
            district = row.get('district')
            state = row.get('state')
            print("IFSC-- {}".format(ifsc))
            if not ifsc:
                break
            bank_object, created = Bank.objects.get_or_create(
                name=bank_name
            )
            branch_defaults = {
                'name': branch,
                'bank': bank_object,
                'address': address,
                'city': city,
                'district': district,
                'state': state    
            }
        
            branch_object, created = Branch.objects.update_or_create(
                ifsc=ifsc, defaults=branch_defaults
            )
            if created:
                print("row created{}".format(branch_defaults))

            # print("No of Rows imported - {} - {} ".format(count, branch_defaults))
            
            count += 1
        messages.success(request, "{} rows imported.".format(count))
            
        return render(request, 'csv_fileupload.html')


Create a templates folder in the root directory and a new HTML file named csv_fileupload.html

TEMPLATE_DIR = os.path.join(BASE_DIR, "templates")
# Add the TEMPLATE_DIR in the TEMPLATES:
'DIRS': [TEMPLATE_DIR, ],

In the csv_fileupload.html we write this code..
<html>
    <head>
        <title>IFSC data import</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" 
        integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" 
        integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
    </head>
    <body>
    <style>
        .import_form{
            padding10px 10px;
            border-radius2px;
            bordersolid 2px #e5eff7;
        }
    </style>
        <div class="import_form col-md-12">
            <form action="" method="POST" enctype="multipart/form-data" 
class="form-horizontal"> 
                <fieldset>
                    <legend>Import IFSC Data</legend> 
                    {% csrf_token %}
                    <div class="form-group">
                        <label for="name" class="col-md-3 col-sm-3 col-xs-12 
                            control-label">File: </label>
                        <div class="col-md-8">
                            <input type="file" name="csv_file" id="csv_file" 
                            required="True" class="form-control">
                        </div>                    
                    </div>
                    <div class="form-group">                    
                        <div class="col-md-3 col-sm-3 col-xs-12 col-md-offset-3" 
                        style="margin-bottom:10px;">
                            <button class="btn btn-primary"> <span 
class="glyphicon glyphicon-upload" style="margin-right:5px;"></span>Upload</button>
                        </div> 
                    </div>
                </fieldset>
            </form>
            {% if messages %}
                <ul>
                    {% for message in messages %}
                        <li style="list-style-type: none ;">
                            {{ message }}
                        </div>
                        </li>
                    {% endfor %}
                </ul>
            {% endif %}
        </div>
        
    </body>
</html>


Add the path in the file/urls.py which is the main URL file:

from django.contrib import admin
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from .views import ImportView

urlpatterns = [
path('admin/', admin.site.urls),
path('upload-csv/',ImportView.as_view(), name='import'"),
]

Now, create a new test.csv file and try to upload it:

test.csv file

name,ifsc,bank,address,city,district,state
RANCHI HATIA MA,ALLA0212214,ALLAHABAD BANK,HATIA MARKET ANEILLIARY CHOWK TUPUNDANA DIST-RANCHI JHARKHAND834003,RANCHI,RANCHI,JHARKHAND







































Comments

Popular posts from this blog

How to create a form and validate the form?

 In this blog we will validate our form by using pure javascript..firstly we have to  make our form in HTML and apply some basic css design so that it looks nice. <!-- Data Validation Data validation is the process of ensuring that user input is clean, correct,  and useful. Typical validation tasks are: has the user filled in all required fields? has the user entered a valid date? has the user entered text in a numeric field? Most often, the purpose of data validation is to ensure correct user input. Validation can be defined by many different methods, and deployed in many different  ways. Server side validation is performed by...

currency converter code in python

 Hello guys, Today in this code i discuss how to convert any currency in python. This is an simple currency converter code. First we have to download the currency data from the google and don't worry i will also provide  this file.. "currency data" Argentine Peso 60.003324 0.016666 Australian Dollar 1.456434 0.686608 Bahraini Dinar 0.376000 2.659574 Botswana Pula 10.748595 0.093035 Brazilian Real 4.165726 0.240054 British Pound 0.769337 1.299820 Bruneian Dollar 1.347741 0.741982 Bulgarian Lev 1.764110 0.566858 Canadian Dollar 1.306715 0.765278 Chilean Peso 773.624384 0.001293 Chinese Yuan Renminbi 6.864835 0.145670 Colombian Peso 3332.909888 0.000300 Croatian Kuna 6.707817 0.149080 Czech Koruna 22.658193 0.044134 Danish Krone 6.740053 0.148367 Emirati Dirham 3.672500 0.272294 Euro 0.901975 1.108678 Hong Kong Dollar 7.769198 0.128713 Hungarian Forint 303.647304 0.003293 Icelandic Krona 123.937684 0.008069 Indian Rupe...

WHAT IS DJANGO AUTHENTICATION?AND HOW TO MANUALLY WRITE THE CODE FOR THE SIGNUP, LOGIN AND LOGOUT?

In this post we see how to manually write the code for the user Registeration , Login and Logout. firstly we have to start a project and than start an app:      django-admin startproject user-authentication     $ cd user-authentication     $ python manage.py startapp accounts Once we have created an app we have to add this app in the INSTALLED_APPS  in settings.py. Than we have to add the path of the accounts app: "main project urls.py" from  django.contrib  import  admin from  django.urls  import  path,include from  django.conf  import  settings urlpatterns = [     path( 'accounts/' ,include( 'accounts.urls' )),     path( 'admin/' , admin.site.urls), ] if  settings.DEBUG:     urlpatterns=urlpatterns+static(settings.MEDIA_URL, document_root =           settings.MEDIA_ROOT)   ...