How to Create Zip File and Download in Django?

Published On: 02/08/2022 | Category: Django Python


Hi Dev,

Now, let's see example of django create zip file. you will learn how to create zip file and download in django. you can understand a concept of django create zip archive file and download it in response. step by step explain create a zip file from a folder and download in django application. Let's see bellow example create zip file from folder and download in django application.

In this example, we will use to zipfile library in python so we can help fully to download zip file.let's see bellow example create zip file from folder and download in django application

You can use these examples with django3 (django 3) version.

let's see below simple example with output:

Step 1 : Create a Project

In this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:

django-admin startproject example
Step 2 : Create a App
python3 manage.py startapp core
Step 3 : Update setting.py

Here, do not forget to register the new app in the settings.py file. Under installed apps, just add ‘core’ to the list:

....
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'core',
]
Step 4 : Database Setup

Next step, we will modify the settings.py file and update the database settings to configure the mydb database:

settings.py
DATABASES = {  
    'default': {  
        'ENGINE': 'django.db.backends.mysql',  
        'NAME': 'example',  
        'USER':'root',  
        'PASSWORD':'root',  
        'HOST':'localhost',  
        'PORT':'3306'  
    }  
}  
Step 5: Create a Model

In this step we will require the database model for storing contacts.Open the core/models.py file and add the following code:

core/models.py
from django.db import models

class Blog(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name

    class Meta:
        ordering = ['-created_at']

After creating these model, you need to create migrations using the following command:

Step 6 : Create a Migrations and Migrate
python manage.py makemigrations
python manage.py migrate
Step 7 : Django’s admin interface

To be able to work with the new model from the admin interface we need to register it. Add this code to the core/admin.py module:

core/admin.py
from django.contrib import admin

from .models import Blog


class BlogAdmin(admin.ModelAdmin):
    pass
admin.site.register(Blog, BlogAdmin)
Step 8 : Creating the Views

In this step, we need to create the views for performing ajax image upload to the database.Open the core/views.py file and add.

core/views.py
import zipfile
from django.http import HttpResponse
from .models import Blog

README_NAME = 'README.md'
README_CONTENT = """
Welcome to our Website!!
"""
ZIPFILE_NAME = 'tuts-station.zip'


def downloadZip(request):
    """Download archive zip file of code snippets"""
    response = HttpResponse(content_type='application/zip')
    zf = zipfile.ZipFile(response, 'w')

    # create the zipfile in memory using writestr
    # add a readme
    zf.writestr(README_NAME, README_CONTENT)

    # retrieve snippets from ORM and them to zipfile
    blogs = Blog.objects.all()
    for blog in blogs:
        zf.writestr(blog.name, blog.description)

    # return as zipfile
    response['Content-Disposition'] = f'attachment; filename={ZIPFILE_NAME}'
    return response
Step 9 : Creating URLs

In this section, we’ll create the urls to access our views.Go to the urls.py core/urls.py file and update it as follows:

core/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('download-zip/', views.downloadZip, name='download')
]

Next, we will require the modify the urls.py your root preoject folder lets update the file.

example/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('core.urls'),
]
Run the Server

In this step, we’ll run the local development server for playing with our app without deploying it to the web.

python manage.py runserver

Next, go to the address with a web browser.

http://localhost:8000/download-zip/
Output

I Hope It will help you....