How to Upload Image Django Admin

In this Django tutorial we will see how to upload image in Django Admin. Before you start you need to install pip pillow.

pip install Pillow

Step 1. Create Django 4 Project

Run below command to create Django project.

django-admin startproject project_name

Now you need to create Django app by running below command.

python manage.py startapp myapp

Add myapp in setting path

# settings.py
INSTALLED_APPS = [
  ...
  'myapp',  #new
  ...

Step 2. Connect to MySql Database

Now you need to configuration add the database credentials. you can use Postgresql database or Mysql for this project we will use mysql.

project_name/settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'database_name',
        'USER': 'user_name',
        'PASSWORD': 'your_password',
        'HOST': 'localhost',  
        'PORT': '3306',      
    }
}

Step 3. Create Models For Myapp

Next, you need to create models for my app.

myapp/models.py

from django.db import models

class Myapp(models.Model):
  title = models.CharField(max_length=200)
  description = models.TextField(blank=True)
  photo_main = models.ImageField(upload_to='photos/%Y/%m/%d/')
  def __str__(self):
    return self.title

Now you need Myapp model in admin.

myapp/admin.py

from django.contrib import admin
from .models import Myapp
from django.utils.safestring import mark_safe

class MyappAdmin(admin.ModelAdmin):
    list_display = ('id', 'title', 'display_image')
    list_display_links = ('id', 'title')

    def display_image(self, obj):
        if obj.photo_main:
            return mark_safe('<img src="{}" height="100" width="100" />'.format(obj.photo_main.url))
        return None
    display_image.allow_tags = True
    display_image.short_description = 'Image'

admin.site.register(Myapp, MyappAdmin)

Step 4. Migrate Database and Create Super User Admin

Next, you need to migrate database run below command.

python manage.py makemigrations
# and
python manage.py migrate

After migration you need to create superuser to access admin panel.

python manage.py createsuperuser

You will be prompted to enter details for the superuser account, including: Username, Email address, Password (twice).

(myenv) ~/path/to/your/project$ python manage.py createsuperuser
Username: admin
Email address: [email protected]
Password:
Password (again):
Superuser created successfully.

Login your admin panel by below url.

http://127.0.0.1:8000/admin

django admin for image upload


Step 5. Add Media URL & Root Path

Next, you need to add MEDIA_URL, MEDIA_ROOT path in project_name/setting.py.

If you are using old Django project then use below code.

project_name/setting.py

# Media Folder Settings
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

Or If you are using new latest Django project then use below code.

MEDIA_URL = "/media/"
MEDIA_ROOT = BASE_DIR / "media"

Now add MEDIA_URL, MEDIA_ROOT in project_name/urls.py.

project_name/urls.py

from django.contrib import admin
from django.urls import path, include # new
from django.conf import settings #new
from django.conf.urls.static import static #new

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('myapp.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # new

Step 6. Upload image and Check

Next, you need Click Myapp and upload image.

upload image in django admin

Now check image show working.

show upload image in django admin

Leave a Reply

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