HOW TO IMPORT CSV IN DJANGO

Spread the love

1. Install django-import-export

pip install django-import-export

2. Add import-export-to INSTALLED_APPS in settings.py

INSTALLED_APPS = (
    ...
    'import_export',
)

3. Set the library to use database transactions when importing data (Optional)

IMPORT_EXPORT_USE_TRANSACTIONS = True

4. Create a resources.py with the follow code

from import_export import resources
from .models import Stock

class StockResource(resources.ModelResource):
    class Meta:
        model = Stock

5. Make template for file upload

<form method="post" enctype="multipart/form-data">
      {% csrf_token %}
      <input type="file" name="myfile"><br><br>
      <button type="submit">Upload</button>
</form>

6. In views.py, Import Dataset and create a view in views.py to import data

from tablib import Dataset
from .resources import StockResource
def upload(request):
    if request.method == 'POST':
        stock_resource = StockResource()
        dataset = Dataset()
        new_stock = request.FILES['csvfile']

        imported_data = dataset.load(new_stock.read())
        result = stock_resource.import_data(dataset, dry_run=True)  # Test data import

        if not result.has_errors():
            stock_resource.import_data(dataset, dry_run=False)  # Run import

    return render(request, 'add_items.html')

7. Make a URL for upload view

url(r'^upload/$', views.upload, name='upload'),

8. Add link to narbar

<li class="nav-item">
        <a class="nav-link" href="/upload">Upload</a>
</li>

Spread the love

About the author

arbadjie

Hi, I'm Abdourahman Badjie, an aspiring developer with obsession for anything coding and networking. This blog is dedicated to helping people learn to develop web applications using django framework.

View all posts

Leave a Reply

Your email address will not be published. Required fields are marked *