Introduction to Django ImageField
The following article provides an outline for Django ImageField. There is a need to store and process images in web applications; the same necessity stays with Django based image applications too. So, the image fields can be flexibly declared and processed in Django. The process of declaring the image-based fields and retrieving the images is comparatively very easy in Django applications. The field which is declared as an image field needs to be associated as an url location in the background, and the specific file will be brought back when a retrieval request is raised. This is how the image level field storage and retrieval take place in the background. Additionally, for whichever records the image is not uploaded, then this null value will be considered.
Syntax of Django ImageField
Given below is the syntax mentioned:
Foreignkey name = models.ImageField(null_argument,blank_argument ,uploadto_argument)
Here the first argument represents a null argument. So this means the value which needs to be maintained for the records for which the records are not updated yet. So for whichever records the image is not uploaded, then this null value will be considered. Next, the blank argument corresponds to the value when a blank is associated to the image field argument.
The last argument is the upload to the argument. This is a very critical argument. This argument determines the location of storage. It means the location at which the loaded documents need to be stored will be considered here. So, from there on, the documents path which is given here will be considered, and the reports will get stored at the location mentioned at this location. This is how the document storage location is carried out.
Creation of Django ImageField
Given below shows the creation of Django ImageField:
1. Changes in Models.py file
As mentioned in the syntax section, the image field needs to be declared in the models.py file. We can notice that the image field is declared as the last field in the model.
Code:
models.py:
from django.db import models
from django.contrib.auth.models import User
# Model variables
# Create your models here.
class Bride(models.Model):
Example_name = models.CharField(max_length=200,null=True)
Example_age = models.IntegerField(null=True)
Example_thegai = models.CharField(max_length=200,null=True)
Example_State = models.CharField(max_length=50,null=True)
Example_District = models.CharField(max_length=50,null=True)
Example_Address = models.TextField(null=True)
Example_Phone = models.BigIntegerField(null=True)
Example_profession = models.CharField(max_length=200,null=True)
Example_salary = models.BigIntegerField(null=True)
Example_Under_Graduation_Degree = models.CharField(max_length=200,null=True)
Example_Under_Graduation_college = models.CharField(max_length=400,null=True)
Example_Post_Graduation_Degree = models.CharField(max_length=200,null=True)
Example_Post_Graduation_college = models.CharField(max_length=400,null=True)
Example_Rasi = models.CharField(max_length=200,null=True)
Example_Nakshatra = models.CharField(max_length=200,null=True)
Image = models.ImageField(null=True,blank=True,upload_to="img/%y")
def __str__(self):
return self.name
2. Changes in Settings.py file
The media root and media URL files need to be updated to the Settings.py file. In addition, the path of the media files needs to be mentioned here to these variables.
Code:
Settings.py:
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'Matrimony.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [Template_DIR,],
'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',
],
},
},
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
STATIC_URL = '/static/'
MEDIA_URL = '/images/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'), ]
print(STATICFILES_DIRS)
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images')
print(STATIC_ROOT)
3. Changes in the url.py file
The media root and document root variable need to be instantiated inside the url.py file as like below.
The changes for the url.py file are mentioned below.
Code:
url.py:
from django.contrib import admin
from django.urls import path
from django.conf.urls import url
from matrimony_pages import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^$',views.Welcome_page,name='Welcome_page'),
url(r'Mainpage/',views.Main_page,name='Main_page'),
url(r'form/',views.form_view,name='form_view'),
url(r"signup/", views.Sign_up_request, name="register"),
url(r"login/", views.login_request, name="login"),
path(r'profile/<str:pk>/',views.profile_page,name='profile'),
url(r'logout/',views.logout_request,name='logout'),
url(r'reg/',views.profile_reg_user,name='reg'),
path(r'update/<str:pk>/',views.form_update,name='update'),
path('admin/', admin.site.urls),
]+ static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
4. Create a view for the form
The image value, when submitted, has to be stored, and when retrieved, it has to be pulled from the database. This can be achieved by means of the object created for the model. The process of doing this is given in the below given views.py section.
Code:
Ex: views.py:
@login_required
def profile_page(request,pk):
context2 = {}
Key_details = Bride.objects.get(id=pk)
Profile_name = Key_details.name
Profile_Age = Key_details.age
Profile_Thegai = Key_details.thegai
Profile_state = Key_details.State
Profile_district = Key_details.District
Profile_Address = Key_details.Address
Profile_Phone = Key_details.Phone
Profile_Profession = Key_details.profession
Profile_Salary = Key_details.salary
Profile_UG = Key_details.Under_Graduation_Degree
Profile_UGC = Key_details.Under_Graduation_college
Profile_PG = Key_details.Post_Graduation_Degree
Profile_PGC = Key_details.Post_Graduation_college
Profile_UG = Key_details.Under_Graduation_Degree
Profile_UGC = Key_details.Under_Graduation_college
Profile_PG = Key_details.Post_Graduation_Degree
Profile_PGC = Key_details.Post_Graduation_college
Profile_Rasi = Key_details.Rasi
Profile_Nakshatra = Key_details.Nakshatra
Profile_Image = Key_details.Image
context2['Age'] = Profile_Age
context2['name'] = Profile_name
context2['thegai'] = Profile_Thegai
context2['State'] = Profile_state
context2['district'] = Profile_district
context2['Address'] = Profile_Address
context2['Phone'] = Profile_Phone
context2['profession'] = Profile_Profession
context2['Under_Graduation_Degree'] = Profile_UG
context2['Under_Graduation_college'] = Profile_UGC
context2['Post_Graduation_Degree'] = Profile_PG
context2['Post_Graduation_college'] = Profile_PGC
context2['Rasi'] = Profile_Rasi
context2['Nakshatra'] = Profile_Nakshatra
context2['Image'] = Profile_Image
print(Key_details.Creator)
print(context2)
return render(request,'Profilepage.html',context2)
5. Formulate an HTML file for displaying the form
Corresponding changes to the HTML pages have to be performed.
Code:
Profilepage.html:
<!DOCTYPE html>
<html style="font-size: 16px;">
<head>
<title>Profile</title>
{% load static %}
<link rel="stylesheet" href="{% static 'admin/css/Formpage.css' %}" media="screen">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1" />
<!-- Script -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body class="body">
<nav class='navbar'>
<div class='navbar_div'>
<a class="navbar" onclick="redirect2()" >Home </a>
<a class="navbar" onclick="redirect2()" >Contact</a>
<a class="navbar" onclick="redirect1()" >Profiles</a>
</div>
</nav>
<div class="formarea">
<br>
{% block content %}
{% if Image %}
<img src="{{Image.url}}" align="right" alt="Image" class="img-thumbnail" style="max-height:200px">
{% else %}
<img src="{% static 'admin/img/default.png' %}" align="right" alt="Image" class="img-thumbnail" style="max-height:200px">
{% endif%}
<br></br>
<h6><strong>Name :    {{name}}</strong></h6>
<h6><strong>Age :    {{Age}}</strong></h6>
<h6><strong>Thegai :    {{thegai}}</strong></h6>
<h6><strong>State :    {{State}}</strong></h6>
<h6><strong>district :    {{district}}</strong></h6>
<h6><strong>Address :    {{Address}}</strong></h6>
<h6><strong>Phone :    {{Phone}}</strong></h6>
<h6><strong>profession :    {{profession}}</strong></h6>
<h6><strong>Under Graduation Degree :    {{Under_Graduation_Degree}}</strong></h6>
<h6><strong>Post_Graduation_Degree :    {{Post_Graduation_Degree}}</strong></h6>
<h6><strong>Post_Graduation_college :    {{Post_Graduation_college}}</strong></h6>
<h6><strong>Rasi :    {{Rasi}}</strong></h6>
<h6><strong>Nakshatra :    {{Nakshatra}}</strong></h6>
{% endblock content %}
</div>
<script>
function form1() {
window.location.href = "http://127.0.0.1:8000/form";
}
function redirect1() {
window.location.href = "http://127.0.0.1:8000/Mainpage";
}
function redirect2() {
window.location.href = "http://127.0.0.1:8000/";
}
function redirect3() {
window.location.href = "http://127.0.0.1:8000/profile";
}
</script>
</body>
</html>
Output:
Conclusion
This article depicts on how the Image field can be flexibly declared in a Django setup, and the changes can be rendered to an html page with the image getting displayed onto the page at the needed position. This process of padding the image can be controlled by means of the division used in the HTML of the page.
Recommended Articles
This is a guide to Django ImageField. Here we discuss the introduction and creation of Django ImageField for better understanding. You may also have a look at the following articles to learn more –
2 Online Courses | 2 Hands-on Projects | 14+ Hours | Verifiable Certificate of Completion
4.5
View Course
Related Courses