Need a minimum Django file upload sample [Close]

Posted by tdelobe on Tue, 07 Jan 2020 05:19:02 +0100

As a novice to Django, it is difficult for me to make an upload application in Django 1.3.I can't find any recent examples/snippets.Can someone publish a minimum but complete (model, view, template) sample code to do this?

#1st floor

I must say I find the documentation on django confusing.Also for the simplest example, why mention the form?An example of what I do in is: -

for key, file in request.FILES.items():
    path =
    dest = open(path, 'w')
    if file.multiple_chunks:
        for c in file.chunks():

The html file looks like the following code, although this example uploads only one file, and the code used to save the file can handle many: -

<form action="/upload_file/" method="post" enctype="multipart/form-data">{% csrf_token %}
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />

These examples are not my code; they were derived from two other examples I found.I'm a relative starter at django, so I probably missed some key points.

#2nd floor

Here it can help you: create a file field in

To upload a file (in

def save_model(self, request, obj, form, change):
    url = "" %(
    url = str(url)

    if url:
        temp_img = NamedTemporaryFile(delete=True)
        filename_img = urlparse(url).path.split('/')[-1],File(temp_img)

And use this field in the template.

#3rd floor

I encountered a similar problem and was resolved by Django administering the site.

# models
class Document(models.Model):
    docfile = models.FileField(upload_to='documents/Temp/%Y/%m/%d')

    def doc_name(self):
        return'/')[-1] # only the name, not full path

# admin
from myapp.models import Document
class DocumentAdmin(admin.ModelAdmin):
    list_display = ('doc_name',), DocumentAdmin)

#4th floor

demonstration edition

To update Answer by AkseliPal n .See github repo , and Django 2 compatible

Minimum Django file upload example

1. Create a django project

Run startproject:

$ startproject sample

Now create a folder (sample):


2. Create an application

Create an application:

$ cd sample
$ python startapp uploader

Now you will create a folder (uploader) that contains the following files:


3. Update

Add'uploader.apps.UploaderConfig'to INSTALLED_APPS at sample/ and add MEDIA_ROOT and MEDIA_URL, that is:

    ...<other apps>...

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

4. Update

Add in sample/

...<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.home, name='imageupload'),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

5. Update

Update uploader/

from django.db import models
from django.forms import ModelForm

class Upload(models.Model):
    pic = models.FileField(upload_to="images/")    
    upload_date=models.DateTimeField(auto_now_add =True)

# FileUpload form class.
class UploadForm(ModelForm):
    class Meta:
        model = Upload
        fields = ('pic',)

6. Update

Update uploader/

from django.shortcuts import render
from uploader.models import UploadForm,Upload
from django.http import HttpResponseRedirect
from django.urls import reverse
# Create your views here.
def home(request):
    if request.method=="POST":
        img = UploadForm(request.POST, request.FILES)       
        if img.is_valid():
            return HttpResponseRedirect(reverse('imageupload'))
    return render(request,'home.html',{'form':img,'images':images})

7. Create Templates

Create a folder template in the folder uploader, and then create a file home.html, sample/uploader/templates/home.html::

<div style="padding:40px;margin:40px;border:1px solid #ccc">
    <form action="#" method="post" enctype="multipart/form-data">
        {% csrf_token %} {{form}} 
        <input type="submit" value="Upload" />
    {% for img in images %}
        {{forloop.counter}}.<a href="{{ img.pic.url }}">{{ }}</a>
        ({{img.upload_date}})<hr />
    {% endfor %}

8. Synchronize databases

Synchronize the database and run the server:

$ python makemigrations
$ python migrate
$ python runserver


#5th floor

I have similar requirements.Most examples on the network require creating models and forms that I don't want to use.This is my final code.

if request.method == 'POST':
    file1 = request.FILES['file']
    contentOfFile =
    if file1:
        return render(request, 'blogapp/Statistics.html', {'file': file1, 'contentOfFile': contentOfFile})

In the uploaded HTML, I wrote:

{% block content %}
    <h1>File content</h1>
    <form action="{% url 'blogapp:uploadComplete'%}" method="post" enctype="multipart/form-data">
         {% csrf_token %}
        <input id="uploadbutton" type="file" value="Browse" name="file" accept="text/csv" />
        <input type="submit" value="Upload" />
    {% endblock %}

Here is the HTML that displays the contents of the file:

{% block content %}
    <h3>File uploaded successfully</h3>
    </br>content = {{contentOfFile}}
{% endblock %}

Topics: Django Python github Database