Uploading Files In Django

March 6, 2023, 7:58 a.m.

django python

Django provides a very simple way to upload files on server. It involves several steps. Here is a brief overview of the process:

1. Create a Django model to represent the data that will be uploaded, including a FileField or ImageField to store the uploaded file.

2. Create a form to allow users to upload files, using Django's built-in FileField or ImageField form fields.

3. Add a view that handles the form submission and saves the uploaded file to the appropriate location on the server.

4. Create a template that displays the form and any uploaded files.

If you haven't install python and django you can start from here Installing python and django

For Quick Setup

Create a virtual environment

python -m venv env

Activate virtual environment

source env/bin/activate

Installing Django

Install python using pip command
pip install django

Creating your first Project

django-admin startproject projectname

Creating your first App

Change to project directory: "cd projectname"

django-admin startapp appname

you see app have its own file structure, hence it is independent of the project. To work with app we need to include it in project

projectname/projectname/settings.py

# Application definition
INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "whitenoise.runserver_nostatic",
    "django.contrib.sitemaps",
    "appname", # <-- add this 
]

Create Model

Create a model to represent the uploaded file:

projectname/appname/models.py

from django.db import models

class Document(models.Model):
    name = models.CharField(max_length=255)
    file = models.FileField(upload_to='uploads/')

Create Form

Create a form to allow users to upload files:

Create a file in app with name 'forms.py'

projectname/appname/forms.py

from django import forms
from .models import Document

class DocumentForm(forms.ModelForm):
    class Meta:
        model = Document
        fields = ('name', 'file')

Create View

Add a view to handle the form submission:

from django.shortcuts import render
from .forms import DocumentForm

def upload(request):
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        
        if form.is_valid():
            form.save()
            return redirect('upload_success')
    else:
        form = DocumentForm()
    return render(request, 'upload.html', {'form': form})

Create Templates

Create a directory called templates within your Django app. This directory contains your html files.

Create an HTML file called index.html within the templates directory:

To learn about how to use django templates, You can learn from here 

{% extends 'base.html' %}
{% block content %}
    <h1>Upload a Document</h1>
    <form method="post" enctype="multipart/form-data">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Upload</button>
    </form>
{% endblock %}

This example should give you a basic understanding of how to upload files in Django. However, keep in mind that there are many variations and additional features that can be added depending on your specific needs.

author image

bracketcoders

A learing portal for your coding interest.

View Profile