File upload and download in django:

Upload:

Setting.py:

include the code in settings.py

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

Urls.py

from django.contrib import admin
from django.urls import path,include
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('file_upload.urls')),
    path('', include('file_download.urls')),
]
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Upload app model:

from django.db import models


class Document(models.Model):
    document = models.FileField(upload_to='documents/')
    uploaded_at = models.DateTimeField(auto_now_add=True)

Upload app url:

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

urlpatterns = [
    
    # path('file_upload/', )
]

upload app views:

from django.shortcuts import render

# Create your views here.

Download app mode:

from django.db import models

# Create your models here.

Download app url:

from django.urls import path
from .import views

urlpatterns = [
    
    path('file_download/', views.file_download, name="file_download")
]

Download app views:

import os

from django.conf import settings
from django.http import HttpResponse


def file_download(request):
    quickbook_path = os.path.join(settings.MEDIA_ROOT, "documents", "Chart_of_Accounts.xlsx")

    with open(quickbook_path, 'rb') as file:
        context = file.read()

    response = HttpResponse(context, content_type='application/vnd.ms-excel')
    response['Content-Disposition'] = 'attachment; filename="abc.xlsx"'

    return response

Comments

Popular posts from this blog

Django Rest Framework Many To Many Relation with intermediate Table Serialization Example