Django tutorial – How to upload images in Django

- Django tutorial

Hey guys! A grand welcome to another great tutorial on Django. In this Django tutorial, I am going to show how to upload images in Python Django.

Uploading images and rendering images on templates are the most important tasks in every web development project. Here we used Django to upload and render images.

Well, If you are a beginner then please read my Django tutorials.

Caution:

I wrote the required settings this article, so go to the media settings section and copy and paste the code in your settings.py file and urls.py.

django tutorial – how to change Django settings file
Django tutorials – how the Django project works

Ok, let’s create the model to upload the image in Django admin. In models.y fie, write these lines.

models.py

from django.db import models

Class Devpyjp(models.Model):
      title = models.CharField(max_length=120)
      img = models.ImageField(upload_to='photos/')

Now, go to your command prompt or shell and execute these lines.

python manage.py makemigrations

python manage.py migrate

Now add your model in the admin.py.

from . models import Devpyjp

admin.site.register(Devpyjp)

Now add images in your admin panel.

If you add images, then now its time to show images on templates. let’s create a view to show images.

views.py:

from . models import Devpyjp

def images_view(request):
    images = Devpyjp.objects..all()
    context={
         'images':images,
           }

    return render(request,'templates/image.html',context)

let’s add this code in your image.html file.

{% for image in images %}

<img src='{{image.img.url}}'>

{% endfor %}

In urls.py file add these below lines.

from .views import images_view

urlpatters =[
path('',images_view,name='home'),
]

You need to configure your url.py file at the app level or project level. If you run the server then you will get your image on the web page.

If you want to learn more about images, read the docs.

I hope you got the idea to upload and images in Django. To get more Django tutorials please subscribe to our newsletter. Thanks for reading.

Leave a Reply