Uploading System Using Python

Simple Uploading System Using Python

Hey there! Uploading files is a common feature in many web applications. Whether it’s user profile pictures, or documents. In this blog, we will walk through creating a simple uploading system using Django, step by step

Prerequisites

Before diving in, ensure you have the following:

  • Python installed on your system.
  • Django installed in your virtual environment.
  • Basic knowledge of Django models, views, and templates.

If you haven’t installed Django yet, you can do so with:

pip install django

Step 1: Set Up the Django Project

First, create a new Django project and app:

django-admin startproject fileUpload 
cd fileUpload 
python manage.py startapp uploader

Next, register your app in the INSTALLED_APPS section of your settings.py file:

INSTALLED_APPS = [
    # Other installed apps
    'uploader',
]

Also, add the following media configurations in settings.py to handle uploaded files:

import os

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

These configurations set up a media URL and root directory to store uploaded files.


Step 2: Define the Model

Create a model to handle uploaded files and images in models.py of the uploader app:

from django.db import models

class UploadedContent(models.Model):
    photo = models.ImageField(upload_to='photos/', blank=True, null=True)
    file = models.FileField(upload_to='files/', blank=True, null=True)
    uploaded_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.photo.name if self.photo else self.file.name

Explanation:

  • photo : Handles uploaded images.
  • file : Handles other uploaded files.
  • upload_at :  Automatically stores the timestamp of the upload.

Run migrations to apply the model to the database:

python manage.py makemigrations 
python manage.py migrate

Step 3: Create a Form

In forms.py create a form for handling file uploads:

from django import forms
from .models import UploadedContent

class UploadContentForm(forms.ModelForm):
    class Meta:
        model = UploadedContent
        fields = ['photo', 'file']
        labels = {
            'photo': 'Upload Photo',
            'file': 'Upload File',
        }

Explanation:

  • This form maps to the UploadContent model.
  • The fields attribute specifies the fields to include in the form.
  • labels provides user-friendly labels for form fields.

Step 4: Create Views

Define a view to handle file uploads and display the uploaded content. Add the following in views.py :

from django.shortcuts import render, redirect
from .forms import UploadContentForm
from .models import UploadedContent

def upload_content(request):
    if request.method == 'POST':
        form = UploadContentForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return redirect('upload_content')
    else:
        form = UploadContentForm()
    uploaded_contents = UploadedContent.objects.all()
    return render(request, 'uploader/upload_content.html', {
        'form': form,
        'uploaded_contents': uploaded_contents,
    })

Explanation:

  • Handles POST requests to save uploaded files to the database.
  • On GET requests, displays the form and previously uploaded content.
  • Retrieves all uploaded content using UploadedContent.objects.all() .

Step 5: Configure URLs

Set up URLs for the uploader app. Create a urls.py file in the uploader directory and add the following:

from django.urls import path
from .views import upload_content

urlpatterns = [
    path('', upload_content, name='upload_content'),
]

Include this app’s URLs in the project’s 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('uploader.urls')),
]

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Explanation:

  • Defines the URL path for the uploader app.
  • Configures MEDIA_URL to serve uploaded files during development.

Step 6: Create the Template

Create a template to render the upload form and display uploaded content. Save the following as uploader/upload_content.html :

<!DOCTYPE html>
<html>
<head>
    <title>Upload Content</title>
</head>
<body>
    <h1>Upload Image or File</h1>
    <form method="post" enctype="multipart/form-data">
        {% csrf_token %}
        {{ form.photo.label_tag }}: {{ form.photo }} <br>
        {{ form.file.label_tag }}: {{ form.file }} <br>
        <button type="submit">Upload</button>
    </form>

    <h2>Uploaded Content</h2>
    <div>
        {% for content in uploaded_contents %}
            <div>
                {% if content.photo %}
                    <a href="{{ content.photo.url }}" target="_blank">
                        <img src="{{ content.photo.url }}" alt="Uploaded Image" width="150">
                    </a>
                    <a href="{{ content.photo.url }}" download="{{ content.photo.name }}">Download Image</a>
                {% endif %}
                {% if content.file %}
                    <p>
                        <a href="{{ content.file.url }}" target="_blank">
                            Download File: {{ content.file.name }}
                        </a>
                    </p>
                {% endif %}
            </div>
        {% endfor %}
    </div>
</body>
</html>

Explanation:

  • Displays a form for uploading images/files.
  • Lists previously uploaded content with options to view or download.

Step 7: Test the Application

Run the Django development server:

python manage.py runserver

Visit http://127.0.0.1:8000/ in your browser. You should see the upload form. Try uploading an image or a file, and you will see it displayed below the form with options to view or download.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top