DEV Community

Muhammad Atif Iqbal
Muhammad Atif Iqbal

Posted on

1 1 1 1 1

How to Create an Image Model in Django (with Settings)

πŸš€ How to Create an Image Model in Django (with Settings)

Django allows you to store and manage images using ImageField. To use this feature, you need to install Pillow, configure Django settings, and set up the database.


READ this complete article on this link

1️⃣ Install Pillow (Required for Image Handling)

Since Django does not include image processing by default, install Pillow:

pip install pillow
Enter fullscreen mode Exit fullscreen mode

2️⃣ Define the Image Model in models.py

Open your models.py inside your Django app and define an image model using ImageField:

from django.db import models
from django.utils import timezone

class ImageModel(models.Model):
    title = models.CharField(max_length=255)  # Title of the image
    image = models.ImageField(upload_to='images/')  # Image will be uploaded to 'media/images/'
    uploaded_at = models.DateTimeField(default=timezone.now)  # Timestamp of the upload

    def __str__(self):
        return self.title  # String representation
Enter fullscreen mode Exit fullscreen mode

3️⃣ Configure settings.py for Media Files

Django does not serve media files by default, so you need to configure settings.py:

import os
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent

# Media settings for image uploads
MEDIA_URL = '/media/'  # URL to access media files
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')  # Location to store uploaded files
Enter fullscreen mode Exit fullscreen mode

4️⃣ Configure urls.py to Serve Media Files

Django needs to be told how to handle media files during development.

Open urls.py and add:

from django.conf import settings
from django.conf.urls.static import static
from django.urls import path
from .views import image_upload

urlpatterns = [
    path('upload/', image_upload, name='image-upload'),  # Image upload view
]

# Serve media files during development
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Enter fullscreen mode Exit fullscreen mode

5️⃣ Apply Migrations

Run these commands to create the necessary database tables:

python manage.py makemigrations
python manage.py migrate
Enter fullscreen mode Exit fullscreen mode

6️⃣ Create a Simple Image Upload View (views.py)

In your views.py, define a simple view to handle image uploads:

from django.shortcuts import render
from .models import ImageModel
from .forms import ImageUploadForm

def image_upload(request):
    if request.method == "POST":
        form = ImageUploadForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
    else:
        form = ImageUploadForm()

    images = ImageModel.objects.all()
    return render(request, 'upload.html', {'form': form, 'images': images})
Enter fullscreen mode Exit fullscreen mode

7️⃣ Create a Form for Image Upload (forms.py)

Django provides forms to handle image uploads. Create a forms.py file inside your app:

from django import forms
from .models import ImageModel

class ImageUploadForm(forms.ModelForm):
    class Meta:
        model = ImageModel
        fields = ['title', 'image']
Enter fullscreen mode Exit fullscreen mode

8️⃣ Create an HTML Upload Template (templates/upload.html)

Inside your app’s templates/ folder, create an upload.html file:

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Image Upload</title>
</head>
<body>
    <h2>Upload an Image</h2>
    <form method="post" enctype="multipart/form-data">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Upload</button>
    </form>

    <h2>Uploaded Images</h2>
    {% for image in images %}
        <img src="{{ image.image.url }}" alt="{{ image.title }}" width="200">
        <p>{{ image.title }}</p>
    {% endfor %}
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

9️⃣ Run the Django Server

Start the Django development server:

python manage.py runserver
Enter fullscreen mode Exit fullscreen mode

Now, go to http://127.0.0.1:8000/upload/ to upload images and see them displayed.


πŸ”Ή Summary

βœ… Install Pillow (pip install pillow)

βœ… Define an image model (ImageField) in models.py

βœ… Configure MEDIA_URL and MEDIA_ROOT in settings.py

βœ… Update urls.py to serve media files

βœ… Create an upload form (forms.py)

βœ… Build an upload view (views.py)

βœ… Design an HTML form for uploading images

Sentry image

See why 4M developers consider Sentry, β€œnot bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)