How to upload a file in Django

0 votes
As a newbie to Django, I am having difficulty making an upload app in Django . May someone post a minimal but complete (Model, View, Template) example code to do so?
Aug 3, 2020 in Python by kartik
• 37,530 points

1 answer to this question.

0 votes

Hello @kartik,

A minimal Django file upload example

1. Create a django project

Run startproject::

$ startproject sample

now a folder(sample) is created.

2. create an app

$ cd sample
$ python startapp uploader

Now a folder(uploader) with these files are created::


3. Update

On sample/ add 'uploader' to INSTALLED_APPS and add MEDIA_ROOT and MEDIA_URL, ie::

    ...<other apps>...      

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

4. Update

in sample/ add::

...<other imports>...
from django.conf import settings
from django.conf.urls.static import static
from uploader import views as uploader_views

urlpatterns = [
    ...<other url patterns>...
    path('', uploader_views.UploadView.as_view(), name='fileupload'),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

5. Update

update uploader/

from django.db import models
class Upload(models.Model):
    upload_file = models.FileField()    
    upload_date = models.DateTimeField(auto_now_add =True)

6. Update

update uploader/

from django.views.generic.edit import CreateView
from django.urls import reverse_lazy
from .models import Upload
class UploadView(CreateView):
    model = Upload
    fields = ['upload_file', ]
    success_url = reverse_lazy('fileupload')
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['documents'] = Upload.objects.all()
        return context

7. create templates

Create a folder sample/uploader/templates/uploader

Create a file upload_form.html ie sample/uploader/templates/uploader/upload_form.html::

<div style="padding:40px;margin:40px;border:1px solid #ccc">
    <h1>Django File Upload</h1>
    <form method="post" enctype="multipart/form-data">
      {% csrf_token %}
      {{ form.as_p }}
      <button type="submit">Submit</button>
    {% for document in documents %}
            <a href="{{ document.upload_file.url }}">{{ }}</a>
            <small>({{ document.upload_file.size|filesizeformat }}) - {{document.upload_date}}</small>
    {% endfor %}

8. Syncronize database

Syncronize database and runserver::

$ python makemigrations
$ python migrate
$ python runserver

visit http://localhost:8000/

Hope it helps!!

Thank You!!

answered Aug 3, 2020 by Niroj
• 82,820 points

Related Questions In Python

0 votes
1 answer

How to order_by a JSON from file in django rest framework?

Hello @kartik, There's an easy way, just override ...READ MORE

answered Jul 1, 2020 in Python by Niroj
• 82,820 points
0 votes
1 answer

How to create and read from a temporary file in Python?

Hi, there is a very simple solution ...READ MORE

answered Jan 29, 2019 in Python by Nymeria
• 3,520 points
0 votes
1 answer

how to delete a file in python?

to delete a file import os os.remove('filename') this will delete ...READ MORE

answered Mar 18, 2019 in Python by Mohammad
• 3,230 points
0 votes
1 answer

how to check for exceptions in a file?

try { if (!file.exists("TextFile1.txt")) throw ...READ MORE

answered Mar 20, 2019 in Python by Mohammad
• 3,230 points
0 votes
1 answer

How to temporarily disable a foreign key constraint in MySQL?

Hello @kartik, To turn off foreign key constraint ...READ MORE

answered Jun 23, 2020 in Python by Niroj
• 82,820 points
0 votes
1 answer

How do I use Django templates without the rest of Django?

Hello @kartik, Let's say you have this important ...READ MORE

answered Jun 23, 2020 in Python by Niroj
• 82,820 points
0 votes
1 answer

How to load a custom JS file in Django admin home?

Hello @kartik, You can override templates/admin/index.html and add the JavaScript ...READ MORE

answered May 14, 2020 in Python by Niroj
• 82,820 points
+1 vote
1 answer

How to create a file and save it to a model's FileField in Django?

Hello @kartik, Basically, a field declared as a FileField, ...READ MORE

answered Jun 30, 2020 in Python by Niroj
• 82,820 points