In: Computer Science
The very first step is to add below code in the settings.py file.
MEDIA_ROOT = os.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
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 name and its image.
In this project we are taking the hotel name and its image from the
user for hotel booking website.
# models.py
class Hotel(models.Model):
name = 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 we upload an image. No need of explicit creation of media directory.
We have to create a forms.py file under image_app, here we are dealing with model form to make content easier to understand
# forms.py
from django import forms
from .models import *
class HotelForm(forms.ModelForm):
class Meta:
model = Hotel
fields = ['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 we specified in the models.py file.
Now create a templates directory under image_app in that we have 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">
<title>Hotel_image</title>
</head>
<body>
<form method = "post"
enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button
type="submit">Upload</button>
</form>
</body>
</html>