Get Images to Upload to Static Folder Django
Prerequisite – Introduction to Django
In most of the websites, we often deal with media data such equally images, files etc. In django we can deal with the images with the help of model field which is ImageField
.
In this commodity, we take created the app image_app
in a sample project named image_upload.
The very first step is to add beneath lawmaking in the settings.py
file.
MEDIA_ROOT
=
os.path.bring together(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 admission 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 nosotros have created a Hotel model which consists of hotel name and its image.
In this project we are taking the hotel proper name and its image 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/'
)
Hither upload_to
will specify, to which directory the images should reside, by default django creates the directory under media directory which will exist automatically created when nosotros upload an image. No need of explicit creation of media directory.
Nosotros have to create a forms.py
file under image_app
, here nosotros are dealing with model form to brand content easier to sympathise.
from
django
import
forms
from
.models
import
*
class
HotelForm(forms.ModelForm):
class
Meta:
model
=
Hotel
fields
=
[
'proper name'
,
'hotel_Main_Img'
]
Django will implicitly handle the form verification's with out declaring explicitly in the script, and it will create the analogous form fields in the page according to model fields nosotros specified in the models.py
file.
This is the advantage of model form.
At present create a templates directory nether 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"
>
<
caput
>
<
meta
charset
=
"UTF-viii"
>
<
championship
>Hotel_image</
title
>
</
head
>
<
body
>
<
course
method
=
"post"
enctype
=
"multipart/form-data"
>
{% csrf_token %}
{{ grade.as_p }}
<
button
blazon
=
"submit"
>Upload</
push
>
</
form
>
</
body
>
</
html
>
When making a POST request, nosotros have to encode the data that forms the body of the request in some way. So, we have to specify the encoding format in the form tag. multipart/course-data
is significantly more complicated but it allows unabridged files to be included in the data.
The csrf_token
is for protection against Cross Site Asking Forgeries.
form.as_p
simply wraps all the elements in HTML paragraph tags. The reward is not having to write a loop in the template to explicitly add HTML to surround each title and field.
In the views.py
under image_app
in that we have to write a view for taking requests from user and gives back some html folio.
from
django.http
import
HttpResponse
from
django.shortcuts
import
render, redirect
from
.forms
import
*
def
hotel_image_view(asking):
if
request.method
=
=
'POST'
:
form
=
HotelForm(request.POST, asking.FILES)
if
class.is_valid():
form.save()
return
redirect(
'success'
)
else
:
form
=
HotelForm()
return
render(request,
'hotel_image_form.html'
, {
'form'
: form})
def
success(asking):
return
HttpResponse(
'successfully uploaded'
)
whenever the hotel_image_view
hits and that request is POST
, nosotros are creating an example of model form course = HotelForm(request.Mail, request.FILES)
image will be stored under asking.FILES
i. If it is valid relieve 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 look like 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, proper name
=
'image_upload'
),
path(
'success'
, success, proper noun
=
'success'
),
]
if
settings.DEBUG:
urlpatterns
+
=
static(settings.MEDIA_URL,
document_root
=
settings.MEDIA_ROOT)
Now brand the migrations and run the server.
When we hitting 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 will exist created, in that images directory will be created and the prototype will be stored under it. Here is the last result.
Now we can write a view for accessing those images, for simplicity let's have case with one image and it is besides applicable for many images.
def
display_hotel_images(request):
if
request.method
=
=
'GET'
:
Hotels
=
Hotel.objects.
all
()
render
render((request,
'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.
Source: https://www.geeksforgeeks.org/python-uploading-images-in-django/
0 Response to "Get Images to Upload to Static Folder Django"
Publicar un comentario