Python Django Profile Photo Upload From Profile Model
Prerequisite – Introduction to Django
In most of the websites, we oftentimes deal with media data such every bit images, files etc. In django we tin can deal with the images with the aid of model field which is ImageField.
In this article, we have created the app image_app in a sample project named image_upload.
The very first pace is to add below code in the settings.py file.
MEDIA_ROOT = bone.path.join(BASE_DIR, 'media' )
MEDIA_URL = '/media/'
MEDIA_ROOT is for server path to store files in the computer.
MEDIA_URL is the reference URL for browser to access the files over Http.
In the urls.py we should edit the configuration like this
from django.conf import settings from django.conf.urls.static import static if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
A sample models.py should be like this, in that we have created a Hotel model which consists of hotel proper noun and its prototype.
In this project nosotros are taking the hotel name and its epitome from the user for hotel booking website.
class Hotel(models.Model):
proper noun = models.CharField(max_length = 50 )
hotel_Main_Img = models.ImageField(upload_to = 'images/' )
Here upload_to will specify, to which directory the images should reside, by default django creates the directory under media directory which will be automatically created when nosotros upload an paradigm. No need of explicit creation of media directory.
Nosotros have to create a forms.py file under image_app, hither we are dealing with model form to make content easier to understand.
from django import forms
from .models import *
grade HotelForm(forms.ModelForm):
grade Meta:
model = Hotel
fields = [ 'proper noun' , 'hotel_Main_Img' ]
Django will implicitly handle the grade verification's with out declaring explicitly in the script, and it will create the analogous course fields in the page according to model fields we specified in the models.py file.
This is the reward of model form.
Now create a templates directory under image_app in that we take to create a html file for uploading the images. HTML file should look like this.
<!DOCTYPE html>
< html lang = "en" >
< head >
< meta charset = "UTF-8" >
< championship >Hotel_image</ title >
</ caput >
< torso >
< form method = "postal service" enctype = "multipart/grade-data" >
{% csrf_token %}
{{ grade.as_p }}
< button type = "submit" >Upload</ button >
</ form >
</ torso >
</ html >
When making a POST asking, we accept to encode the data that forms the torso of the request in some mode. Then, we have to specify the encoding format in the form tag. multipart/class-data is significantly more complicated only it allows entire files to be included in the information.
The csrf_token is for protection confronting Cross Site Request Forgeries.
form.as_p simply wraps all the elements in HTML paragraph tags. The advantage is not having to write a loop in the template to explicitly add HTML to environs each title and field.
In the views.py under image_app in that nosotros accept to write a view for taking requests from user and gives back some html page.
from django.http import HttpResponse
from django.shortcuts import render, redirect
from .forms import *
def hotel_image_view(request):
if asking.method = = 'POST' :
form = HotelForm(asking.Mail service, asking.FILES)
if class.is_valid():
course.save()
return redirect( 'success' )
else :
form = HotelForm()
return render(request, 'hotel_image_form.html' , { 'grade' : form})
def success(request):
render HttpResponse( 'successfully uploaded' )
whenever the hotel_image_view hits and that request is POST, we are creating an example of model course form = HotelForm(request.Postal service, asking.FILES) epitome volition exist stored under request.FILES i. If it is valid save into the database and redirects to success url which indicates successful uploading of the image. If the method is not POST we are rendering with html template created.
urls.py will wait similar this –
from django.contrib import admin
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from .views import *
urlpatterns = [
path( 'image_upload' , hotel_image_view, name = 'image_upload' ),
path( 'success' , success, name = 'success' ),
]
if settings.DEBUG:
urlpatterns + = static(settings.MEDIA_URL,
document_root = settings.MEDIA_ROOT)
Now brand the migrations and run the server.
When nosotros striking the URL in the browser, in this way it looks.
After uploading the image it will show success.
At present in the project directory media directory volition be created, in that images directory volition be created and the image volition exist stored under it. Here is the concluding result.
Last output stored in the database
Now we tin can write a view for accessing those images, for simplicity let'due south take example with ane prototype and information technology is as well applicative for many images.
def display_hotel_images(request):
if request.method = = 'GET' :
Hotels = Hotel.objects. all ()
return return((asking, 'display_hotel_images.html' ,
{ 'hotel_images' : Hotels}))
A sample html file template for displaying images.
Insert the url path in the urls.py file
# urls.py path('hotel_images', display_hotel_images, name = 'hotel_images'), Here is the final view on the browser when we try to admission the image.
Hotel Image
Source: https://www.geeksforgeeks.org/python-uploading-images-in-django/
Post a Comment for "Python Django Profile Photo Upload From Profile Model"