Django

Creating Views in Django

Creating Views in Django

Django views are an important part of its MVT (Model-View-Template) structure. The views are part of the user interface that simply renders the HTML/CSS templates for a web page. Django views are of two types:

  • Function-Based Views: These views are written with the help of python functions that receive HttpRequest objects and return an HttpResponse Object. Function-based views are simply divided into 4 categories such as – CRUD (Create, Retrieve, Update, Delete). 

Creating Function based view:

To create a function based view, we will have to create a model first with the help of the following code:
 

from django.db import models
class GreatLearningModel (models.Model):
title = models.CharField(max_length = 200)
description = models.TextField()
def __str__(self):
return self.title

After creating the model using the code above, the following two commands need to be run to create a database:

Python manage.py makemigrations

Python manage.py migrate

Now, we’ll create some instances of the model using the python shell window. First, you need to run the following command from bash,

Python manage.py shell

After opening the shell window, enter the following commands:

>>> from gl.models import GreatLearningModel
>>> GreatLearningModel.objects.create(
title = “title1”,
description = “description1”).save()
>>> GreatLearningModel.objects.create(
title = “title2”,
description = “description2”).save()
>>> GreatLearningModel.objects.create(
title = “title3”,
description = “description3”).save()

After creating the model using the code above, you need to register its data in the admin panel. To register the model, you need to enter details in the
 

greatlearning/admin.py file,
from django.contrib import admin
from .models import GreatLearningModel
admin.site.register(GreatLearningModel)

Now this will register the model in Django. And you can verify the instances using:

http://localhost:8000/admin/greatlearning/greatlearningmodel/

Now, we’ll create views in
 

greatlearning/views.py,
from django.shortcuts import render
from .models import GreatLearningModel
def views_list(request):
context = {}
context[“dset”] = GreatLearningModel.objects.all()
return render (request, “list_view.html”, context
)

This way you can create function based views in Django. 

  • Class Based Views: Class-based views give alternatives for creating views. These kinds of views are simple and easy to manage. Class-based views are much simple than function-based views. For example – A function-based view with thousands of lines of code can be converted to class-based view with a few lines of code. 

Creating Class Based View:

To create a class-based view, we will have to navigate to the views.py file under the ‘greatlearning’ folder and use the following code:

from django.views.generic.list import ListView
from .models import GreatLearningModel
class GreatLearningModel (ListView):
model = GreatLearningModel

After creating the view, you can create a URL path to map the view by using the following code in greatlearning/urls.py:

from django.urls import path
from .views import GreatLearningList
url_patterns = [
path(‘’, GeeksList.as_view()),
]

Django - URL Mapping

In the previous section, we just created some working views. Those views can be accessed with the help of a URL. Here in this section, we will do the URL mapping for our views which can be done by editing the file urls.py under our project directory. You need to make the following changes in this file:

from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns(‘’,
url(r’^admin’, include(admin.site.urls)),
url(r’^great/’, ‘firstapp.views.great’, name = ‘great’),
)

The mapping is composed of three elements that are described below:

Pattern: Patterns can be created by using the python ‘re’ module. 

The path of the view: The path is the same for importing the module. 

Name: The URL reversing can be done using named URL patterns and after that, the view can be accessed via view URL e.g.: http://127.0.0.1/great

Django - Template System

The Django framework is very useful for creating dynamic HTML pages with the help of its template system. A template consists of pre-developed parts of HTML output that can be directly used to create HTML pages. Python coding cannot be done in HTML files as the browser cannot interpret python code. Therefore, the Django template engine is used in order to differentiate the python and HTML code that makes it possible to create dynamic web pages. 

Let’s see how you can configure Django templates by providing some information in the settings.py file under your project folder (firstproject/settings.py)

TEMPLATES = [
{
‘BACKEND’ : ‘django.template.backend.django.Django’
‘DIRS’ : [os.path.join(BASE_DIR,’gltemp’)],
‘APP_DIRS’ : True,
‘OPTIONS’ : {
‘context_processors’ : [
‘django.contrib.auth.context_processors.auth’,
‘django.contrib.messages.context_processors.rr’,
‘django.template.context_processors.request’,
‘django.template.context_processors.debug’
],
},
},
]

This way we created our template directory with the name ‘gltemp’ and the Django templates system automatically looks for the templates folder under INSTALLED_APPS. 

Django Template Language: The Django template makes use of its syntax while dealing with variables, expressions, and HTML tags. Here we will understand the concept with the help of an example where the template deals with Variables. The variables with a context are accessible by using double curly braces {{}}. Let’s see the example below:

 

The tutorial name is {{tutorialName}}.

>>The tutorial name is Django Tutorial.

For creating a variable and storing values in it, you need to use the view.py file with the following code:

from django.shortcuts import render
from django.template import loader
from django.http import HttpResponse
def index(request):
template = loader.get_template(‘index.html’)
tutorial = {
‘tutorialName’: ‘Django Tutorial’
}
return HttpResponse(template.render(tutorial))

Now we will use the variable in our HTML file, i.e. //index.html

This way you can refer to the variables in your HTML file. 

<!DOCTYPE html>
<html lang = “en”>
<head>
<meta charset = “UTF-8”>
<title>GL DjangoTemplate Example</title>
</head>
<body>
<h1>The tutorial is provided by Great Learning</h1>
<h2>And the name of the tutorial is: {{tutorialName}}</h2>
</body>
</html>

Django – Models

A model is used for creating tables or collections in the database. It comes as a built-in feature in Django Models. Alternatively, we can say that Django Model is the SQL for the databases we use in our Django project. However, SQL is a structured query language and is complex for creating, deleting, and updating entries in the database. But Django models are very simple for creating and organizing tasks and tables into models. 

Some useful points about Django Models:

  • Each Django model is a subclass in Python : Django.db.models.Model
  • Django provides access to automatically generated APIs of databases which makes it more efficient. 
  • Attributes in the Django model are used to represent database fields. 

 

Now, let us see how you can create Django models:

from django.db import models
class GreatModel (models.Model):
website = models.CharField(max_length = 50)
title = models.CharField(max_length = 25)
phone = models.IntegerField()
email = models.CharField(max_length = 40)
tutorialName = models.CharField(max_length = 30)
class SubGreatModel:
database_table = “GreatModel”

In Django models, each model has inherited from django.db.models.Model

In our model class, we declared 5 attributes that include 4 CharFields and 1 IntegerField that can be found in the database table. 

We also created a subclass with the name SubGreatModel with the attribute name database_table that defines the actual table in our model. 

After creating the model, let us initiate the Django model to generate the actual database with the following command:

$python manage.py syncdb

This way you can create and sync your database table in Django models. 

Django - Page Redirection

Page redirection refers to the redirection of a web page from another page on the occurrence of an action. A simple example of page redirection can be when the user logs into his account, he is often redirected to a different page for his personal dashboard. To implement this redirection method, you need an argument. Let’s see the views we created for the app will look like this:

def hello(request):
today = datetime.datetime.now().date()
weekDays = [‘Sun’, ‘Mon’, ‘Tue’, ‘Wed’, ‘Thu’, ‘Fri’, ‘Sat’]
return render (request, “great.html”, {“today” : today, “week_days”: weekdays})
def checkArticle (request, articleNo):
msg = “The article number is : %s” %articleNo
return HttpResponse (msg)
def checkArticles (request, year, month):
msg = “The articles are published on : %s%s: %(year,month)
return HttpResponse(msg)

Now, we are going to change the view to redirect it to another page gldjangoproject.com and to do that we have to redirect checkArticle to the internal directory where the page exists, i.e. ‘/firstapp/articles’. The following settings will apply in the view.py file for the same:

from django.shortcuts import render, redirect
from django.http import HttpResponse
import datetime
def hello(request):
today = datetime.datetime.now().date()
weekDays = [‘Sun’, ‘Mon’, ‘Tue’, ‘Wed’, ‘Thu’, ‘Fri’, ‘Sat’]
return redirect(“https://www.djangoproject.com”)
def checkArticle (request, articleNo):
msg = “The article number is : %s” %articleNo
return redirect(checkArticles, year = “2023”, month = “01”)
def checkArticles (request, year, month):
msg = “The articles are published on : %s%s: %(year,month)
return HttpResponse(msg)

The above changes will redirect the page to the URL we provided in the redirect method. Here, we imported the redirect from django.shortcuts and then redirected it to the official website of Django by passing the URL to the ‘redirect’ method. 

Django - Sending E-mails

Django provides a simple and easy way to send e-mail. As it is Python based framework, it also needs to import smtplib which will help you to start sending e-mails. To implement an e-mail setup in your Django project, you need to provide the following details in the settings.py file:

EMAIL_HOST : Here you need to provide SMTP server details.

EMAIL_PORT : The server port needs to be used here for sending e-mails.

EMAIL_HOST_USER : This attribute will require login credentials for your SMTP server.

EMAIL_HOST_PASSWORD : Here you need to provide the password of your SMTP server account.

EMAIL_USE_TLS or EMAIL_USE_SSL : It will be set to True if the connection is secure. 

Let’s understand how you can setup Django for sending mail:

To do that, you need to create a view as follows:

from django.core.mail import send_mail
from django.http import HttpResponse
def simpleMail (request, emailto):
msg = send_mail (“Hey learners”, “Are you learning well?”, “admin@greatlearning.com”, [emailto])
return HttpResponse (‘%s’ %msg)

By using the code described above, a view will be created with the name simpleMail that you can use to send emails. The parameters that we used in the example above are described below:

  • subject : Here you need to provide the subject of your mail. In our case, we used – “Hey learners”.
  • message : For this parameter, you need to provide the message or body of your mail, i.e. “Are you learning well?” in our case.
  • from_email : You need to add your email address here. (admin@greatlearning.com)
  • recipient_list : See the example above where we used ‘emailto’. There you need to provide the recipient’s address. 

Now as we created our view simpleMail, we need a URL to access it. So, let’s create a URL by using the following settings in the urls.py file:
 

from django.conf.urls import patterns, url
urlpatterns = patterns (‘firstapp.views’, url(r’^simpleMail/(?P<emailto>[/w.%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4})/’, ‘simpleMail’, name = ‘simpleMail’),)

Now, to access the view, you need to use the URL: http://127.0.0.1:8000/firstapp/simplemail/admin@greatlearning.com/ 

Django - Generic Views

Whenever we need to create a static page of a website, we may need to write views in our Django app and that may consume a long time. There’s an easy way to do that by setting simple views of Django that are called Generic views. However, generic views are not functions, but there are a set of classes that provides generic views and you can find them in django.views.generic. 

Let’s try to use generic views for static pages. First, we will create an index.html file with some HTML code:

<html>
<body>
<h2>This page is created using HTML only.</h2>
</body>
</html>

Now, we are going to change the settings in the views.py file:

from django.shortcuts import render
def static (request):
return render (request, ‘index.html’, {})

Also, the urls.py file will look like this:

from django.conf.urls import patterns, url
url_patterns = patterns (“firstapp.views”, url(r’^static/’, ‘static’, name = ‘static’), )

Now, we are going to use generic views and for that views.py file will contain the information as follows:

from django.views.generic import TemplateView
class StaticView (TemplateView):
template_name = “index.html”
After this, we need to re-edit the urls.py file with the following details:
from firstapp.views import StaticView
from django.conf.urls import patterns
url_patterns = patterns(“firstapp.views”, (r’^static/$’, StaticView.as_view() ), )

Now, you can access the generic view you just created for that static HTML page (index.html) with the help of the URL:

http://127.0.0.1:8000/firstapp/static/ 

 

Top course recommendations for you

    Docker Swarm
    1 hrs
    Beginner
    1.8K+ Learners
    4.5  (126)
    Factorial Program in C
    2 hrs
    Beginner
    5.3K+ Learners
    4.46  (556)
    Jenkins Tutorial
    1 hrs
    Beginner
    8.7K+ Learners
    4.53  (710)
    Dockerize Spring Boot Application
    1 hrs
    Intermediate
    4.1K+ Learners
    4.46  (325)
    Python Data Structures
    1 hrs
    Beginner
    31.8K+ Learners
    4.5  (2546)
    Fibonacci Series in Java
    2 hrs
    Beginner
    2.8K+ Learners
    4.39  (69)
    Priority Queue in C++
    1 hrs
    Beginner
    2.2K+ Learners
    4.38  (110)
    Introduction to MATLAB
    2 hrs
    Beginner
    22.5K+ Learners
    4.41  (1798)
    Packages in Python
    1 hrs
    Beginner
    7.4K+ Learners
    4.33  (568)
    Palindrome in Python
    2 hrs
    Beginner
    2.9K+ Learners
    4.65  (92)