File Uploads - potatoscript/django GitHub Wiki
In Django, working with files and images is a common task. Whether it's allowing users to upload images, processing documents, or serving files like PDFs or Excel sheets, Django makes it easy to handle file uploads and management.
In this tutorial, we’ll go step-by-step through the process of handling file uploads and serving them using Django. We will also learn how to work with images, such as displaying them on web pages or resizing them.
Before diving into handling files and images, you need to configure Django to work with these types of content.
First, ensure that you have the necessary settings to store uploaded files.
-
Define media directories:
In
settings.py
, specify the locations for storing files and images uploaded by users.# settings.py MEDIA_URL = '/media/' # This is the URL path for accessing uploaded files MEDIA_ROOT = BASE_DIR / 'media' # This is the directory where files are stored
-
MEDIA_URL
: The base URL for serving uploaded media files (e.g., images, documents). -
MEDIA_ROOT
: The file system path where media files are stored on your server.
-
-
Ensure
django.conf.urls.static
is included:Django needs to serve static files (like images) during development. In
urls.py
, add:from django.conf import settings from django.conf.urls.static import static urlpatterns = [ # Your other URL patterns ] # Serve media files in development (useful when DEBUG=True) if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
You need to create a model that will handle file or image uploads.
Let’s create a model that stores an uploaded image. You will use Django’s ImageField
to store images.
# models.py
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
image = models.ImageField(upload_to='products/', blank=True, null=True)
def __str__(self):
return self.name
In this example:
-
name
: The name of the product. -
description
: A text field for a product description. -
image
: The image for the product, which is uploaded to theproducts/
directory inside the media folder. -
The
upload_to
argument specifies the folder withinMEDIA_ROOT
where the uploaded files should go.
To allow users to upload files through a form, you’ll need to create a form in Django that includes an ImageField
or FileField
.
Let’s create a form for the Product
model we just created.
# forms.py
from django import forms
from .models import Product
class ProductForm(forms.ModelForm):
class Meta:
model = Product
fields = ['name', 'description', 'image']
This ProductForm
will allow users to input product details and upload an image.
Now, we need a view to handle the form, display it to users, and process the uploaded file when submitted.
# views.py
from django.shortcuts import render, redirect
from .forms import ProductForm
def product_upload(request):
if request.method == 'POST':
form = ProductForm(request.POST, request.FILES)
if form.is_valid():
form.save() # Save the product with the uploaded image
return redirect('product_list') # Redirect to another page after upload
else:
form = ProductForm()
return render(request, 'product_upload.html', {'form': form})
In this view:
- We use
request.FILES
to handle file uploads. - If the form is valid, we save the data and uploaded image to the database.
Next, let’s create a template to display the form.
<!-- templates/product_upload.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Product Upload</title>
</head>
<body>
<h1>Upload a New Product</h1>
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Upload Product</button>
</form>
</body>
</html>
-
enctype="multipart/form-data"
is important for handling file uploads in forms. -
{{ form.as_p }}
displays the form fields, including the file input.
After the image is uploaded, we’ll display it on a webpage.
# views.py
from django.shortcuts import render
from .models import Product
def product_list(request):
products = Product.objects.all() # Get all products from the database
return render(request, 'product_list.html', {'products': products})
<!-- templates/product_list.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Product List</title>
</head>
<body>
<h1>All Products</h1>
<ul>
{% for product in products %}
<li>
<h2>{{ product.name }}</h2>
<p>{{ product.description }}</p>
{% if product.image %}
<img src="{{ product.image.url }}" alt="{{ product.name }}" width="200">
{% else %}
<p>No image available</p>
{% endif %}
</li>
{% endfor %}
</ul>
</body>
</html>
In this template:
- We loop through all products and display their details.
- We use
{{ product.image.url }}
to generate the URL for the uploaded image.
-
Run your development server:
python manage.py runserver
-
Visit the file upload form by navigating to
http://127.0.0.1:8000/product/upload/
(or your custom URL). -
Upload an image using the form and submit it.
-
Check the list of products at
http://127.0.0.1:8000/products/
to see the uploaded image displayed.
You can also handle other types of files, such as PDFs or Word documents. The process is almost the same as handling images but with the use of Django's FileField
.
# models.py
class Document(models.Model):
title = models.CharField(max_length=100)
file = models.FileField(upload_to='documents/', blank=True, null=True)
def __str__(self):
return self.title
# forms.py
class DocumentForm(forms.ModelForm):
class Meta:
model = Document
fields = ['title', 'file']
# views.py
def document_upload(request):
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('document_list')
else:
form = DocumentForm()
return render(request, 'document_upload.html', {'form': form})
<!-- templates/document_list.html -->
{% for document in documents %}
<p>{{ document.title }} - <a href="{{ document.file.url }}">Download</a></p>
{% endfor %}
This example allows users to upload PDF files, and other users can download them via the link.
Step | What Happens |
---|---|
1. Setting up Media Directories | Configure MEDIA_URL and MEDIA_ROOT in settings.py to store uploaded files. |
2. Creating a Model | Create a model with an ImageField or FileField to store files or images. |
3. Creating a ModelForm | Create a form to handle file or image uploads using ModelForm . |
4. Creating Views for Upload | Handle file uploads in views and save the data to the database. |
5. Displaying Files | Show uploaded files or images on your website using the file’s URL. |
6. Handling Other File Types | Handle other file types (e.g., PDFs) with FileField . |