How to upload photos using Django app
One of the most appealing features of modern applications is the ability to store images. Images such as photos, illustrations, and animations add visual appeal to the app.
Here's how to upload photos to your Django app without compromising security .
Requirement to prepare
Before you start uploading photos, make sure you meet the following requirements:
- Install Python.
- Install Pip.
- Install Pipenv.
- Install Django.
- You have a Django app that needs images.
Now that you have the necessary dependencies, start uploading images to the application right away.
1. Install Pillow
Django has an ImageField in its model. This field contains the image uploaded in a specific location in the file system, not the database. Pillow is a Python library that inspects images in ImageField.
To install pillow , use the command below:
pipenv install pillow
If you are using venv , use this command:
pip install pillow
2. Create templates
Create an ImageField reference in the database. Then add the upload_to argument in this model. That argument specifies a storage location in the file system.
class Profile(models.Model): name = models.CharField(max_length=80, blank=True) bio = models.TextField(max_length=254, blank=True) profile_picture = models.ImageField(upload_to='photos/') def __str__(self): return f'{self.user.username} profile'
The method at the end helps to convert the data to string.
Next, migrate and commit the new changes to the database. Then you need to edit the project settings.
3. Add media URL to project settings
Navigate to project settings. Under the heading # Static files (CSS, JavaScript, Images) , add the media URL.
# https://docs.djangoproject.com/en/4.0/howto/static-files/ BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' # Các vị trí bổ sung cho collectstatic để tìm thấy file tĩnh. STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) # STATICFILES_STORAGE = MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Adding a media URL to the settings defines a specific route for displaying uploaded images. This media file contains an image of the application. The path should look like this: 127.0.0.1:8000/media/profile/image.jpg .
Update the TEMPLATES array in the project settings. Add django.template.context_processors.media to the templates array.
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.media' ], }, }, ]
The processor's media settings help with loading uploaded images in application templates.
4. Add Media Root to URL
Next, you need to add the MEDIA_ROOT route to your app's URL. This will help upload the uploaded image to the programming server.
First, import the project settings from the django.conf module and a static function . Then add a static route urlpatterns showing the location of the uploaded file.
from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ path('', views.index, name = 'index'), path('profile', views.profile, name='profile'), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) urlpatterns += staticfiles_urlpatterns()
5. Check photo upload
Next, run the server:
python manage.py runserver
If there are no errors, navigate to the Django admin panel by adding the admin route to the base URL, http://127.0.0.1:8000/admin .
Inside the admin panel, when you click on the Profile module , you will see an added image field at the bottom.
When uploading an image, you will see a new folder created in the app folder named media . When you open this folder, you will see the photos uploaded through the admin panel.
6. Show uploaded photos
You will update the profile template to show the account profile picture.
You would add an img tag and fill it with the profile_picture attribute . ImageField has a URL property that provides the absolute URL for the file. You can define the shape and appearance of images using CSS classes.
{% extends "base.html" %} {% load static %} {% block content %} {% endblock %}
You can run this server to download images. Then check the template in the browser to see the displayed image.
Django gives you an easy way to upload images to your app. Django has a separate field on this model that adds and checks the file type before upload.
ImageField provides the absolute path for the file system to store the image. This helps speed up the application, and at the same time, ensures that the database is not compromised by malicious files.
You should read it
- How to use AWS S3 Bucket to store static and media files in Django
- How to Add Search to a Django App
- How to build an authentication system in Django using OAuth
- How to Implement ChatGPT in Django
- How to override default template in django-allauth
- How to Create a CRUD App with Django's Class Based Viewers
- Using Django API is easy with built-in templates
- Model Inheritance là gì trong Django?
May be interested
- How to use Face Animation to convert still portraits to GIFsthe face animation website relies on nero ai's artificial intelligence technology to process images and convert static portraits into animated images. the image processing process on face animation is also very fast.
- 5 reasons Web3 is less secure than Web 2.0web3 is the blockchain-based version of the internet. it's the evolution of web 2.0, focused on making data decentralized.
- 8 tools to see the old version of any websitewhether you're just curious to see old web pages or want to find information that no longer exists on the web, knowing how to view older versions of websites can be helpful.
- Instructions to create a heart avatar with a name aroundin this article you will get more ideas for avatar pictures with heart avatars with names around or whatever name you want.
- Instructions for creating photos of sunset effects onlinesunset photos are loved by many people because of the artistry they bring. if you love this type of sunset photo, you can create text with a sunset effect with a very simple implementation.
- Instructions to create a heart collage onlineheart collage is a way for us to express our feelings to each other. and you can also use this heart collage for special occasions.