Django
Django
Django
</form>
</body>
</html>
I am assuming that you already have a firm grip on HTML. If that is not the case,
then you can learn HTML within 30 minutes by clicking here.
03:08 - Creating Buttons :
We will use the HTML <button> tag for creating buttons.Open index.html and type
the following code :
<button type='submit'> Analyze Text</button>
Here, we have created only one button, i.e., Analyze Text. But, we will include more
buttons in the future.
</form>
Restart the Django development server. From now, any text entered in the text area
will be sent to the removepunc endpoint. For example, I entered "Code With Harry"
in the text area and then clicked on the Analyze Text button. In the image below, you
can see that "Code With Harry" is sent to the removepunc endpoint.
With this, we have successfully created the home page of our website. I hope each
and every step is working fine on your end.
# views.py
# I have created this file - Harry
from django.http import HttpResponse
from django.shortcuts import render
def index(request):
return render(request, 'index.html')
# return HttpResponse("Home")
def removepunc(request):
#Get the text
djtext = request.GET.get('text', 'default')
print(djtext)
#Analyze the text
return HttpResponse("remove punc")
def capfirst(request):
return HttpResponse("capitalize first")
def newlineremove(request):
return HttpResponse("newline remove first")
def spaceremove(request):
return HttpResponse("space remover back")
def charcount(request):
return HttpResponse("charcount ")
# urls.py
"""textutils URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from . import views
]
index.html code as described/written in the video
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Template is working</title>
</head>
<body>
<h1>Welcome to the text analyazer. Enter your text below</h1>
<form action='/removepunc' method='get'>
<textarea name='text' style='margin: 0px; width: 721px; height:
93px;'></textarea>
<button type='submit'> Analyze Text</button>
</form>
</body>
</html>
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index, name='index'),
path('analyze', views.analyze, name='analyze')
]
In the views.py file, delete all the view functions that we made earlier and define only one function,
called analyze. Type the following code:
def analyze(request):
Now, open the index.html file and type the following code for creating a checkbox:
<input type="checkbox" name="removepunc"> Remove Punctuations<br>
Restart your server and check whether all the things are working correctly or not.
Step 3: Name the file as analyze.html and press enter. Now, open analyze.html and type the below
code :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Analyzing Your Text...</title>
</head>
<body>
<h1>Your Analyzed Text - {{ purpose }}</h1>
<p>
{{ analyzed_text }}
</p>
</body>
</html>
In the above code, we have created a <h1> tag into which we have passed a variable named
"purpose." We have also made a paragraph tag into which we have passed another variable called
"analyzed_text."
if removepunc == "on":
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
analyzed = ""
for char in djtext:
if char not in punctuations:
analyzed = analyzed + char
params = {'purpose': 'Removed Punctuations', 'analyzed_text': analyzed}
return render(request, 'analyze.html', params)
else:
return HttpResponse('Error')
Let's understand the above code one line at a time. First of all, we are checking if the removepunc
checkbox is on or off. If it is off, then the control will come to the else statement, and an error
message will be printed on the user's screen. Otherwise, the if block of the code will be executed.
Inside the if block, we have stored all the punctuation marks in a punctuations variable and made an
empty variable named analyzed. When the user checks on the removepunc checkbox, iteration will
be performed on the user's text with the help of a for loop. Finally, all the punctuations will be
removed from the text entered by the user.
Example: I wrote the text "Remove;';' all ;./ the punctuations;#" and then clicked on the Analyzed
Text button after checking on the removepunc checkbox. In the image given below, you can see that
all the punctuations are removed.
YOU'VE DONE IT. YOU'VE MADE YOUR VERY FIRST WORKING WEBSITE!!! I'm so proud
of you. We will continue our Django series in the next tutorial. I hope you all are falling in love
with Django ❤️
# Views.py
# I have created this file - Harry
from django.http import HttpResponse
from django.shortcuts import render
def index(request):
return render(request, 'index.html')
# return HttpResponse("Home")
def analyze(request):
#Get the text
djtext = request.GET.get('text', 'default')
else:
return HttpResponse("Error")
# def capfirst(request):
# return HttpResponse("capitalize first")
#
# def newlineremove(request):
# return HttpResponse("newline remove first")
#
#
# def spaceremove(request):
# return HttpResponse("space remover back")
#
# def charcount(request):
# return HttpResponse("charcount ")
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index, name='index'),
path('analyze', views.analyze, name='analyze')
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Text Utils</title>
</head>
<body>
<h1>Welcome to the text analyzer. Enter your text below</h1>
<form action='/analyze' method='get'>
<textarea name='text' style='margin: 0px; width: 721px; height:
93px;'></textarea><br>
</form>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Analyzing Your Text...</title>
</head>
<body>
<h1>Your Analyzed Text - {{ purpose }}</h1>
<p>
{{ analyzed_text }}
</p>
</body>
</html>
Problem Statement :
You are supposed to create a personal navigator for the top 5 websites that you use most.
You should be able to access all the five websites directly through your development
environment of Django.
Expected Output :
Solution :
Type the below code in the views.py file :
def ex1(request):
s=''' Navigation Bar <br> </h2>
<a href= "https://www.youtube.com/playlist?
list=PLu0W_9lII9ah7DDtYtflgwMwpT3xmjXY9" > Django Code With Harry Bhai </a><br>
<a href="https://www.facebook.com/"> Facebook </a> <br>
<a href="https://www.flipkart.com/"> Flipkart </a> <br>
<a href="https://www.hindustantimes.com/"> News </a> <br>
<a href="https://www.google.com/"> Google </a> <br>
reutrn HttpResponse(s)
# Views.py
def index(request):
return render(request, 'index.html')
# return HttpResponse("Home")
def ex1(request):
sites = ['''<h1>For Entertainment </h1><a href = "https://www.youtube.com"
>youtube video</a>''',
'''<h1>For Interaction </h1><a href = "https://www.facebook.com"
>Facebook</a>''',
'''<h1>For Insight </h1><a href = "https://www.ted.com/talks"
>Ted Talk</a>''',
'''<h1>For Internship </h1><a href="https://internshala.com"
>Intenship</a>''',
]
return HttpResponse((sites))
Now, open the views.py file and type the following code:
fullcaps=request.GET.get('fullcaps','off')
In the above code, we have made a variable named fullcaps which stores the on or off the value of
the fullcaps checkbox. Now, type the following code in views.py :
elif fullcaps=="on":
analyzed=""
for char in djtext:
analyzed=analyzed+char.upper()
params = {'purpose': 'Change To Uppercase', 'analyzed_text': analyzed}
return render(request, 'analyze.html', params)
else:
return HttpResponse('Error')
Let's understand the above code line by line. We have used the elif loop to check whether the
fullcaps checkbox is on or off. After that, we have made an empty string variable named analyzed.
When the user checks on the fullcaps checkbox, then the for loop inside the elif loop will be
executed, and an iteration will be performed on djtext. On performing iteration, the text will be
converted into the upper case with the help of the upper() function. Example: I wrote "change to
upper case" and checked on the UPPERCASE check button. You can see in the image below that
the text is converted into upper case.
06:10 - Logic Building For newlineremover :
Now, we will write code for removing a new line from the text entered by the user. Open index.html
and type the following code:
<input type="checkbox" name="newlineremover"> New Line Remover<br>
In the above code, we are using the same approach that we have used for creating other buttons. We
are using an elif loop to check whether the newlineremover checkbox is turned on or off by the user.
When the user checks on the newlineremover, then the for loop will be executed, and the new line
will be removed with the help of a newline character("\n").
In the above code, we have used elif to check whether the extraspaceremover is on or off. If the
checkbox is on, then the for loop will be executed, and extra spaces will be removed with the help
of the built-in function enumerate(). For example, I wrote, "Remove all the extra spaces." I checked
on the Extra Spaces Remover button. You can see in the image below that all the extra spaces are
removed.
With this, we have successfully added some amazing functionalities to our textutils website. This
tutorial ends here, and I will see you in the next tutorial. Feel free to ask your questions in QnA.
views.py code as described/written in the video
# Views.py
# I have created this file - Harry
from django.http import HttpResponse
from django.shortcuts import render
def index(request):
return render(request, 'index.html')
# return HttpResponse("Home")
def ex1(request):
sites = ['''<h1>For Entertainment </h1> <a href="https://www.youtube.com/">
Youtube Videos</a> ''',
'''<h1>For Interaction </h1> <a href="https://www.facebook.com/">
Facebook</a> ''',
'''<h1>For Insight </h1> <a href="https://www.ted.com/talks"> Ted
Talks</a> ''',
'''<h1>For Internship </h1> <a
href="https://www.internshala.com">Internship</a> ''']
return HttpResponse((sites))
def analyze(request):
#Get the text
djtext = request.GET.get('text', 'default')
elif(fullcaps=="on"):
analyzed = ""
for char in djtext:
analyzed = analyzed + char.upper()
elif(extraspaceremover=="on"):
analyzed = ""
for index, char in enumerate(djtext):
if not(djtext[index] == " " and djtext[index+1]==" "):
analyzed = analyzed + char
# def capfirst(request):
# return HttpResponse("capitalize first")
#
# def newlineremove(request):
# return HttpResponse("newline remove first")
#
#
# def spaceremove(request):
# return HttpResponse("space remover back")
#
# def charcount(request):
# return HttpResponse("charcount ")
# Urls.py
"""textutils URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from . import views
</form>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Analyzing Your Text...</title>
</head>
<body>
<h1>Your Analyzed Text - {{ purpose }}</h1>
<p>
{{ analyzed_text }}
</p>
</body>
</html>
Output:
Notice that text is changed to upper case, and all the punctuations marks are also
removed.
What Is Bootstrap?
• Bootstrap is a front-end development framework.
• It is a library of HTML, CSS, and JS used to create modern websites and web applications.
Sounds great! But, you might be thinking that you don't know anything about it, so how you will
use it. Don't worry! Click here to learn Bootstrap in one hour.
After copying the starter template, open the index.html file, and paste the starter template. You can
also copy the starter template from below :
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-
to-fit=no">
<title>Hello, world!</title>
</head>
<body>
<h1>Hello, world!</h1>
After copying the code, paste this code in index.html. After pasting, your website will look
something like this :
Use the same code to make more switches. But, do not forget to change the switch id.
12:20 - Adding Analyze Text Button :
Type the code given below to add the analyze text button :
<button type="submit" class="btn btn-dark mt-2">Analyze Text</button>
After successfully adding buttons and switches, add the action attribute in the form tag. Write the
following code :
<form action='/analyze' method='get'>
With this, we have successfully added Bootstrap to the home page of our textutils website. But, we
have not included Bootstrap on the endpoints pages of our website. So, let's add Boostrap on the
endpoint pages.
<title>Text Utils</title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand" href="#">TextUtils.in</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-
target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-
expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavDropdown">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span
class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">About Us</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Contact Us</a>
</li>
</ul>
</div>
<form class="form-inline">
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-
label="Search">
<button class="btn btn-outline-success my-2 my-sm-0"
type="submit">Search</button>
</form>
</nav>
In the above code, we have added the starter template and navigation bar of Bootstrap. After that,
we have passed the analyzed_text and purpose variable inside the div container.
And that's how we completely changed the overall look of our website without even writing a single
line of code. Isn't it amazing? That's why I love Bootstrap, and you should too! This tutorial ends
here, and we have also completed the development of our textutils website.
def index(request):
return render(request, 'index.html')
# return HttpResponse("Home")
def ex1(request):
sites = ['''<h1>For Entertainment </h1> <a href="https://www.youtube.com/">
Youtube Videos</a> ''',
'''<h1>For Interaction </h1> <a href="https://www.facebook.com/">
Facebook</a> ''',
'''<h1>For Insight </h1> <a href="https://www.ted.com/talks"> Ted
Talks</a> ''',
'''<h1>For Internship </h1> <a
href="https://www.internshala.com">Internship</a> ''']
return HttpResponse((sites))
def analyze(request):
#Get the text
djtext = request.GET.get('text', 'default')
elif(fullcaps=="on"):
analyzed = ""
for char in djtext:
analyzed = analyzed + char.upper()
elif(extraspaceremover=="on"):
analyzed = ""
for index, char in enumerate(djtext):
if not(djtext[index] == " " and djtext[index+1]==" "):
analyzed = analyzed + char
# def capfirst(request):
# return HttpResponse("capitalize first")
#
# def newlineremove(request):
# return HttpResponse("newline remove first")
#
#
# def spaceremove(request):
# return HttpResponse("space remover back")
#
# def charcount(request):
# return HttpResponse("charcount ")
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-
to-fit=no">
<title>Text Utils</title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand" href="#">TextUtils.in</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-
target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-
expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavDropdown">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span
class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">About Us</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Contact Us</a>
</li>
</ul>
</div>
<form class="form-inline">
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-
label="Search">
<button class="btn btn-outline-success my-2 my-sm-0"
type="submit">Search</button>
</form>
</nav>
<div class="container">
<div class="form-group">
<label for="exampleFormControlTextarea1">Enter your text here and let Text
Utils do the magic</label>
<textarea class="form-control" name='text' id="exampleFormControlTextarea1"
rows="9"></textarea>
</div>
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-
to-fit=no">
</ul>
</div>
<form class="form-inline">
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-
label="Search">
<button class="btn btn-outline-success my-2 my-sm-0"
type="submit">Search</button>
</form>
</nav>
<div class="container">
</p>
</div>
In the image given below, you can see that the text that I entered was changed to uppercase. But, all
the new lines were also removed automatically. So, why are we facing this issue? I would suggest
you spend some time in finding out the reason of this bug. We will discuss the cause and solution of
this bug further in this tutorial.
If you have figured out the reason for this bug, then I must say that you are a good programmer, and
all the basic concepts are crystal clear to you. Now, let's discuss the cause:
This error is coming from our analyze.html file. In our analyze.html file, we have directly dumped
the analyzed_text variable inside the paragraph tag. But, it is the default property of HTML to chop
off the new line character inside the paragraph tag. To stop this, HTML requires us to use a <pre>
tag, which indicates that the text is preformatted.
Open analyze.html and add the <pre> tag :
<div class="container mt-5">
<h1>Your Analyzed Text -- {{purpose}}</h1>
<p>
<pre> {{ analyzed_text}} </pre>
</p>
</div>
Now, let's check whether everything is working correctly or not. Again, I entered the text and turned
on the UPPERCASE button. Now, you can see in the image given below that newlines are still
there, and HTML is not removing them automatically.
And that's how we quickly fixed the bug on our textutils website. I hope all the concepts are crystal
clear to you. Ask your queries in the QnA section.
# Views.py
# I have created this file - Harry
from django.http import HttpResponse
from django.shortcuts import render
def index(request):
return render(request, 'index.html')
# return HttpResponse("Home")
def ex1(request):
sites = ['''<h1>For Entertainment </h1> <a href="https://www.youtube.com/">
Youtube Videos</a> ''',
'''<h1>For Interaction </h1> <a href="https://www.facebook.com/">
Facebook</a> ''',
'''<h1>For Insight </h1> <a href="https://www.ted.com/talks"> Ted
Talks</a> ''',
'''<h1>For Internship </h1> <a
href="https://www.internshala.com">Internship</a> ''']
return HttpResponse((sites))
def analyze(request):
#Get the text
djtext = request.POST.get('text', 'default')
print(djtext)
elif(fullcaps=="on"):
analyzed = ""
for char in djtext:
analyzed = analyzed + char.upper()
elif(extraspaceremover=="on"):
analyzed = ""
for index, char in enumerate(djtext):
if not(djtext[index] == " " and djtext[index+1]==" "):
analyzed = analyzed + char
# def capfirst(request):
# return HttpResponse("capitalize first")
#
# def newlineremove(request):
# return HttpResponse("newline remove first")
#
#
# def spaceremove(request):
# return HttpResponse("space remover back")
#
# def charcount(request):
# return HttpResponse("charcount ")
index.html code as described/written in the video
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-
to-fit=no">
<title>Text Utils</title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand" href="#">TextUtils.in</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-
target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-
expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavDropdown">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span
class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">About Us</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Contact Us</a>
</li>
</ul>
</div>
<form class="form-inline">
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-
label="Search">
<button class="btn btn-outline-success my-2 my-sm-0"
type="submit">Search</button>
</form>
</nav>
<div class="container">
<form action='/analyze' method='get'>
<div class="form-group">
<label for="exampleFormControlTextarea1">Enter your text here and let Text
Utils do the magic</label>
<textarea class="form-control" name='text' id="exampleFormControlTextarea1"
rows="9"></textarea>
</div>
</ul>
</div>
<form class="form-inline">
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-
label="Search">
<button class="btn btn-outline-success my-2 my-sm-0"
type="submit">Search</button>
</form>
</nav>
<div class="container">
</p>
</div>