Exception Handling in Python: An Introduction(GUIDE)

Hey, Coders, Today, I’m going to explain Exception Handling in Python. In this article, I’m going to tell you that How you can Raise an Exception in Python and handle them to prevent your program from termination.

What Is Exception ?

During the program execution, Sometimes your programs terminated due to some unusual error occur, Which also known as Exceptions. Now, It’s the responsibility of the program to handle these exception and prevent the program from termination.

To prevent our program from termination, We have to handle these exceptions using try and except block. But before that let me show you a simple example of program that got terminated due to an error.

In this given program, I declared an age variable to get an integer input. But instead of entering integer value, I’ll enter string value. Therefore, our programs will get terminated by ValueError exception like this:

PROGRAM 1:
age = int(input("Enter Your Age: "))
Enter Your Age: ds

Traceback (most recent call last):
  File "C:/Users/Prashant Karn/Desktop/HK2LITE PROGRAMS/Pythons/Exceptions/Exceptions.py", line 1, in <module>
    age = int(input("Enter Your Age: "))
ValueError: invalid literal for int() with base 10: 'ds'

Process finished with exit code 1

In this above code, You can see that our program got terminated and displayed ValueError.

Exception Handling In Python

In above code, You just saw that How our program terminated due to an ValueError exception. Therefore, To prevent our program from these kind of termination, we have to handle these exception. It’s the responsibility of programmers to handle these exception and display friendly message to users.

To Handling Exception in Python, We need to use “try” and “except” clause. These clause will allow programmers to display friendly message. It will also prevent your program from termination.

PROGRAM 2:

Here, I’m going to Handle the exception of Program 1. First, Let me show you my program that I’ve written to handle error:

try:
    age = int(input("Enter Your Age: "))
except ValueError:
    print("Enter Valid Age")
Enter Your Age: four
Enter Valid Age

In this above code, You can see that I’ve used try block and insert my program inside the try block. Then I’ve use except clause to display a friendly message.

In try block, You have to insert your statement or program. Then In except block, You have to define an error with except clause that you want to handle. Just like here, we want to handle ValueError exception. Therefore, We will use ValueError with except clause. Inside this clause, just print your message.

Handle Different Exception At One Time:

In Python, We have lot of different exception that occurs due to different types of errors. You can check all Python exception from their Official Website: Click Here

Here, You can also handle different type of exception at one time, which belongs to same message. In above code, We handled an exception to prevent wrong data type entries error. In that same code, we will define an additional exception called “ZeroDivisionError”. ZeroDivisionError Exception occur when someone try to divide any integer with 0.

    try:
        age = int(input("Enter Your Age: "))
        num1 = 10/age
    except (ValueError, ZeroDivisionError):
        print("Enter Valid Age")

In this above, You can see that we handled our “ZeroDivisionError” along with “ValueError” exception inside except clause.

You May Also Like: Classes Introduction in Python Programming

That’s it for today. It’s just a basic overview introduction of Exception and Handling Exception in Python. If you wanna get updated with such kind of programming related post then please don’t forget to subscribe our blog via email.

Thank’s To Read…

You may also like

Django Beginner Project – Random Password Generator

Hey Coders, In today’s article, We’re going to build a beautiful basic project in Django Framework. I think It will be one of the best project for all newbie beginners. So, If you just entered and have learned some basic things about Django then I think this Random Password Generator project would be best for you.

Before starting this Django Beginner Project, Let me tell you that what we’re going to build inside this Project.

PROJECT DESCRIPTION:

In this project, First we’re going to create two page. In which, one page will be take input and then other page will display processed data. In this project, we would dealing with only two file e.g: urls.py and views.py. Here, we don’t need to create any database for this project.

So, Without wasting any time, Let’s start our Django beginner project to build the Random Password Generator.

Building Password Generator Django Web App:

Let’s begin our project…

Before following this tutorial, Make sure you have installed Django Package. After then you can follow up this tutorial.

First, Let’s create our project. I’m going to give “pass_gen” name to my Django Project. Because we’re building Password Generator Website. To create a project you’ve to type following command:

django-admin startproject pass_gen

Now, the following command will create the project with folder name “pass_gen”. Now, open this project folder inside your IDE. I’m going to use my favorite PyCharm IDE, Which is best for all sort of python related codes.

In Your main Project folder, You will see “pass_gen” folder again. Inside this pass_gen folder, You will have all required python files e.g settings.py, urls.py, models.py etc.

In Django, we can create different apps for different operations inside our main project. So, here we’re going to create our app called “generator” inside our main project . To create an app you have to type following command inside your project folder.

python manage.py startapp generator
Listing Django APP in Settings.py

Once you’ve created your app then you have to list it inside settings.py app. In settings.py, you will see INSTALLED_APPS section, where you will list your generator app. So, first open settings.py that you will get inside your main app folder. Here, list you can list your created apps e.g

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'generator',
]

Now get inside you generator app folder, where you will different types python file e.g: views.py, models.py, admin.py, etc. But here, we’ll only play with views.py file.

Now It’s time to create pages. Here, we need two pages:

  • home(Page): Here, we will display a form that will take input from user that which types of website they want. Once the user will hit the generate button then it will send them to password page.
  • password(Page): Here, We will display users generated password according as per their given inputs.
Home(Page):
Django Beginner Project
Password(Page)
Random Password Generator

Now I’m going to setup url for both pages.

Setting Up Url Paths:

Now let’s setup our url path for both pages. To setup url path you need to get inside your urls.py file of main root folder. Here, you need to edit your code like this:

pass_gen/urls.py:
from django.urls import path
from generator import views

urlpatterns = [
    path('', views.home, name="home"),
    path('password/', views.password, name="password"),
]

In this above, we’ve removed already defined admin path. Because we don’t need admin page in this project. Here, I’ve defined two path, but before that I’ve imported views files from generator.

In each path, we need to define 3 parameters e.g: url path, function and name. For home, We have defined our path like (‘ ‘), which means homepage, then views.home defines that whenever someone would visit our page then it will run home function of views file. Finally name=”home”, which means we can call our url using their respective names. As same we did with password/ url path.

Creating Templates:

Now Let’s create our required tempates, so that later on our views function can call them. Here we will create 3 html file.

  • Home.html: It will be used to display our form to generate password.
  • password.html: It will be used to display user random generated password
  • base.html: It will be our base html, which means any html file can inherit this template.

But first, we need to create our folders, inside which we will place our all folders and files related to templates.

First create a folder called “templates” inside your generator folder. Now inside this folder again create a folder called “generator“. Inside this generator folder, we will place our all html file.

Project Structure

I’ve created all those required html below, that you could see.

Base.html

This is our base.html file, In which I’ve used some bootstrap for customization and a simple black navbar.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
    <title>Password Generator</title>
</head>
<body>
<!-- As a link -->
<nav class="navbar navbar-dark bg-dark">
  <a class="navbar-brand" href="{% url 'home' %}">Pass Gen</a>
</nav>

<div class="container">
    <div class="jumbotron">
        {% block content %}

        {% endblock %}
    </div>
</div>
</body>
</html>
Home.html

This is our home.html, where we’ve inherited template of our base.html. In this html code, I’ve defined form with action to password page. Inside this form, I’ve defined select input and some check boxes for conditions. Inside each and every tag, I gave a name, so that later on we could apply condition over these name in our views file.

Because we’ve pointed our form action to “password” path. Therefore, whenever someone would enter hit then it will send all required information to password page.

{% extends 'generator/base.html' %}
{% block content %}

<h1>PASSWORD GENERATOR</h1>

<form action="{% url 'password' %}">
    <div class="form-group">
    <label>Length</label>
    <select name="length" class="form-control">
      <option>8</option>
      <option>9</option>
      <option>10</option>
      <option>11</option>
      <option>12</option>
      <option>13</option>
      <option>14</option>
      <option>15</option>
      <option>16</option>
    </select>
    </div>
    <div class="form-check">
      <input class="form-check-input" type="checkbox" name="uppercase">
      <label class="form-check-label">
        UpperCase
      </label>
        <br>
      <input class="form-check-input" type="checkbox" name="numbers">
      <label class="form-check-label">
        Numbers
      </label>
        <br>
      <input class="form-check-input" type="checkbox" name="special">
      <label class="form-check-label">
        Special
      </label>
    </div>
    <button class="btn btn-success" type="submit">Generate Password</button>
</form>

{% endblock %}
Password.html

Here, we simply defined our password section, where user generated password will be shown. Here, we’ve accessed our password using {{password}} key, that we’re going to define in views.py section.

{% extends 'generator/base.html' %}
{% block content %}

<h5 class="alert alert-success">Your Generatred Password: <strong>{{password}}</strong></h5>


{% endblock %}
Views.py

Now let’s define home and password function inside our generator/views.py. So that url path could call these functions whenever someone will request or visit our page.

Before defining our function, let me show you my view.py code. After then I’ll explain each and everything explicitly.

views.py(code)
from django.shortcuts import render
import random

def home(request):
    return render(request, 'generator/home.html')

def password(request):
    characters = list('abcdefghijklmnopqrstuvwxyz')

    if request.GET.get('uppercase'):
        characters.extend(list('ABCDEFGHIJKLMNOPQRSTUVWXYZ'))

    if request.GET.get('numbers'):
        characters.extend(list('0123456789'))

    if request.GET.get('special'):
        characters.extend(list('!@#$%^&*()?><:;'))

    length = int(request.GET.get("length"))

    thepassword = ''
    for x in range(length):
        thepassword += random.choice(characters)

    return render(request, 'generator/password.html', {"password":thepassword})

Let me define each and every section of above code explicitly.

First, we’ll talk about def home(request) function. Here, you could see that I’ve simply returned a html page located at ‘generator/home.html’ path. Here, you need to note that I didn’t include templates folder with path. Because templates folder has already joint with every html files.

Now, Let’s define our def password() function. It’s the main function because it will check all condition entered by users and then will return a random password. Here, we will use random module to generate random password.

Inside password function, we will create list called characters that will contain all small letters from a to z. It will be default list. Random will be choose out it, when no one’s actually checked any condition e.g uppercase, special and numbers.

After then we will check ‘uppercase‘ condition, Here, we will use If condition. which means someone has checked uppercase checkbox then It will extend previous characters list with adding uppercase A-Z letters.

Now same It will check for ‘special’ and ‘numbers’.

After checking all these typical condition, we will define our length variable in integer type. This length variable will take data by using GET method that user had entered in length select section of home page.

Now we will define a empty string called thepassword, that will store our generated password after processing.

After then we will simply iterate using for loop, where length will be used as a range. Under this for loop you will see, In each iteration It will simply add a random character from characters list with previous “thepassword” string.

You May Also Like: Web Scraping With BeautifulSoup4 Tutorial

Running Your Project:

Now You need to run your project using following command:

python manage.py runserver

Now It will run your server on your localhost https://127.0.0.1:8000. Visit on your localhost and then you will see your site is live.

If you would till face any problem then please comment below. We will try to solve your problem as soon as possible.

Thank’s To Read…

You may also like

How To Add Email Subscription To WordPress Blog

Hi Bloggers, do you want to add an email subscription to your WordPress blog, then you’re at a right place. Because In this Article, I’m going to Guide you that How You can add beautiful and customizable email subscription forms to you WordPress website. And Later on How you could send emails to your subscribers.

Basically, We’re going to divide this whole process into two part.

  1. First Step: How to add Email Subscription to Your website?
  2. Second Step: How To send emails to your subscribers.

So, Without further late, let’s get start our tutorial to add Email subscription To your WP Blog.

Add Email Subscription To Your WordPress Blog:

In this phase, we’re going to add beautiful and attractive Email subscription form to our website. After adding subscription form to our blog, It will only collect emails from subscribers. In second phase, I’ll tell that you can send emails to those subscribers.

Let’s add Our email Form to WP Blog. We’re going to use convertful plugin of WordPress to add Subscription form to our blog.

Convertful is most useful service to that allows you to add attractive and eye catching Form to your WordPress.

1. Create An Account On Convertful Website

First of all, You have to create an account on ConvertFul Website. Here, You can proceed with their free(0$/month) plan. Because It’s an okay for a new and average WordPress blogs.

Create an account on ConvetFul

Now select the Free Plan and Follow all the instruction to create an account. And Your Unique username, firstname and password

Now We will see dashboard like this:

Add Site On Convertful for Email Subscription Forms

Now fill up all the all the required* fields e.g your blog url, Site Platform(WordPress) and Category. After then click on Add Site. Now you will be redirected to this page:

connecting converful to WordPress

Now, You’re site is successfully added to your convertful account.

2. Connecting WordPress With ConvertFul Account:

Now It’s time to add Your WordPress blog with ConvertFul account so that you can add and display your subscription forms.

First You have to install a Plugin called Convertful to your WordPress. Therefore, Open your WordPress dashboard and add plugin name convertful and activate it.

Adding  Email Subscription To Worpress Blog

Once You’ve activated the convetful plugin then simply click on connect to convertful button.

connect forms to wordpress

Now It will redirect you to this page. Here, just click on approve button to connect you converful account with wordpress.

3. Creating And Adding Widget Forms To Your WordPress

Once you’ve successfully connect your wordpress site to your convertful account then you can create and add form.

First, Let’s create a Pop-Up Email Subscription form to your WordPress website. To Create A form, Click on Create Widget button

Creating Email Subscription form For WordPress website

Now, You need to select type of form that you want to display at you website. There are bunch of different types of form e.g Inline Forms, Pop-Up Form, Discount Forms, Etc. Here, You’ll get ready made designed form that you can customize as per your requirement.

Because, We want to add Pop-Up Subscription form, therefore, we will select pop-up form.

Adding Pop-Up email subscription form to wordpress

Now, You need to select a template of form that you want to add. I’ve selected this template of subscription form.

creating pop-up for email subscription

Now, you can customize above form according to your requirements. After some customization, My form look like this:

Customize Email Subscription Form

Once you customization would be done, then just simply click on “Display Rules” tab that you could see on top section. Here, you can add condition of your pop-up form, which means like when you want to call your pop-up form. I want to show pop-up form to my subscribers, when they would read 40% of my articles.

Rules to displaying forms

Once you’ve done then just click on save changes button to save and “inactive” toggle to active your forms. It’s all done, Now whenever someone would visit my website and read 40% of my content then he will get pop-up form like this.

How To Add Email Subscription Form To WordPress Blog

That’s it, Now If the user enter their detail and click on subscribe then their email will be add to you convertful account. you can see your subscriber list in subscribers tab of convertful dashboard.

Subscriber adding in WordPress

But As I previously said that Convetful is only used to collect Email’s from your subscribers. Therefore, once you got email list of your subscriber then you need to use other mail provider services to send emails to those subscriber.

In second phase, we’re going to show you how you send an email to those subscribers. Here, we will use MailChimp Email service to send emails to our subscribers.

You May Also Like: How To Start A Free Blog in 2020(GUIDE)

Send E-mails to Subscribers using MailChimp:

MailChimp is one of the best email service provider that will help you to send an email your subscriber. Here, we will also select their free plan. In this free plan you can send an email upto 2000 subscribers. So, If your subscriber base is larger than 2000 then you proceed with other plans.

But Free plan is enough for new and average websites. Let’s start our second phase of this guide…

1. Create An Account On MailChimp

First of all, You have to create an account on MailChimp to use their services. Go To Click On the button given below and all the details to open an Account.

One you’ve opened your account successfully then select your plan. Here, I’m proceeding with free plan, where we can have upto 2000 subscribers.

Sending Mails With MailChimp to Our subscribers

Now Click on Complete button and enter details about your website and then click continue.

Now you’re ready to go.

2. Connect MailChimp With ConvertFul Account

we’ve just created our mailchimp account successfully. So, now it’s time to connect our MailChimp account with ConvertFul Account. After then, we will receive all of the subscriber’s email details in our mailchimp account too.

To Connect MailChimp with ConvertFul, You have to visit convertful dashboard again. Here, you will be see Integration Tab

Adding Email Subscription Form To WordPress

Under this Integration Tab, You will see add integration button, click on it. Now select email service provider. Here, we want to connect our mailchimp account, therefor, we will be choose mailchimp here. After then simply click on connect button and login with your mailchimp account.

Connect MailChimp For Add Email Subscription with wordpress

Once you’ve connected your account successfully then you will redirected to the new page.

Note: You need to off “request double-opt in” checkbox. (To Disable confirmation email)(Important)

Now we’ve connected our mailchimp account with convertful successfully.

3. Sending Emails To Subscribers

It’s a final step, where we will send our emails to our subscribers. But before send an email, make sure you should have at least one subscriber.

Here, I’ve subscribed our website with someone’s else email details. You can also do that to check your service is working properly or not.

To Send an email, Go to you mailchimp account and click on “Audience tab” and then click on View Contacts button. Here, You will see email and details of your subscribers.

Mailchimp sending an emails to subscribers

Now Let’s start sending emails to our subscribers that we’ve got from our email subscription form.

To send an email to your subscribers, First, you need to create an email. To create an Email, First click Create Button that you will get at top-left corner. There you will get drop-down list, then you need to click on email option.

Creating an email to send to subscribers

Now, here you will see pop-up window, where you need to enter campaign name and then click begin. It will take you to this new page, where you have to fill up all details related to email.

Adding Email Subscription In WordPress Blog

Here, You will see different option:

  • To(Add Recipients): Here, you need to select your subscribers group
  • From(Add From): Sender means your email address.
  • Subject(Add Subject): Add subject of your email.
  • Content(Design Email): Here, you need to design your email that you want to send to your subscribers.

Before Sending an Email, First you have to design it. To design you mail, Click on design email option and you will be redirected to new page. Here, you can select your template and edit as per you wish.

template of email

Select your template and customize it as you want.

MailChimp Email Customizations

Now, Click on “continue” and then click on “Send” button.

send an email, email subscription in wordpress

Click on “Send Now” button and your message will be sent successfully like this.

How To Add Email Subscription in WordPress

It’s all done. Your message has been sent successfully to all your subscribers. Now when your subscriber will check their email, they will get an email something like this

Adding email subscription in wordpress

So that’s it for today. I hope all of you will like this article about how to add email subscription to your wordpress blog

If you liked our article then please subscribe our blog to get such kind of blogging stuffs. Please don’t forget to share this article with your friends.

Thank’s To Read…

You may also like

Web Scraping With BeautifulSoup in Python(GUIDE)

Web Scraping With BeautifulSoup 4 :

In Python, If we want to gather data from someone’s website then we basically use APIs. But there are lot of websites, where they don’t have APIs. In such case, we can use scraping technique to scrap data from someone’s website. We can perform web scraping with BeautifulSoup Python module.

Basically, BeautifulSoup is one of the useful module to scrape data from any website. Basically, It’s parse the html content of any web page and then scrap data within specific Html Tag.

Today, I’m going to give you full guide about How you can use BS4 module to scrap data from any website.

Installing Required Modules:

Here, we have to install two required modules to do web scraping. You can install these modules by using pip commands. These modules are:

  1. requests: install by using command: “pip install requests
  2. beautifulsoup4: install by using command: “pip install beautifulsoup4

requests module is used to get html web page of any website that we want to scrape. Then beautifulsoup4 module is used to scrape data from websites.

Now, Let’s begin our tutorial about web scraping with beautifulsoup 4:

Web Scraping With BS4:

Let me tell you that what data from which website we’re going to scrap today. Basically, we’re going to perform our web scraping on StackOverflow.

I want to scrap recent questions and their details asked on StackOverflow website. First of all we have to import some modules that we just installed. We will import BeautifulSoup class from bs4 module and after then we will import requests module.

from bs4 import BeautifulSoup
import requests

Now, we will create an object from our request module to get html of web page that we want to scrape. Let’s give this object a name “response”. Here, You have to enter website url under get method of request module like this:

response = requests.get("https://stackoverflow.com/questions/")

Now we will create an object name “soup” from BeautifulSoup Class. In this BeautifulSoup, we have to fill two parameters. First parameter is used for fetching html content and second is used for parsing that html file.

For first parameter, we will use response object that contains our web page html. we will enter like response.text(for html content). In second parameter, we will enter “html.parse“, because we’re parsing html content like:

soup = BeautifulSoup(response.text, "html.parser")
Inspecting Html:

Now, You have to visit that website that you want to scrap like SatackOverFlow/Questions. After then right click on element and you will see Inspect element option.

Web Scraping With BeautifulSoup in Python

Now you will see all html tags of that web page. Here, you need to find all those html tags that contains your data that you want to scrap.

Web Scraping in Python

In this above image, You can see that our questions id contains all of the question of this web page. But we want only questions and their details, therefore, we will be looking inside tags that contains our question. Here, You can see that all of questions have same div tag with class name = question-summary.

Now, we will use select function in soup object to contains all html with these class name=”question-summary” like this:

questions = soup.select(".question-summary")

In this above code, It will return a list that we’ve stored in questions variable. Now, we need to dig inside this div to find all those data. I’ve inspected and found that all questions are lies under the ahref link, which has a class name “question-hyperlink“.

We know that above questions is a kind of list, therefore we can access each element separately through an index no like:

print(questions[0].select(".question-hyperlink"))

But this above code will return a list. Therefore, you have to use select_one instead of select. But It will still return you question with anchor tags instead of plain text. Therefore, If you want to get plain text then you have to use getText() function in last like:

print(questions[0].select_one(".question-hyperlink").getText())

Result: Now you will simply get your question of index no. 0 from question list.

But Here, we want all of the questions from our web page. We have to use for loops to iterate over questions list. Basically I’m going to iterate all questions in question from list:

print(question.select_one(".question-hyperlink").getText())

Run The Code and You will get such type of result in your terminal:

Web Scraping with BeautifulSoup4 Python Module

Congratulations, You’ve successfully scraped questions from StackOverFlow. I’ve final code for you, where I’ve also added vote-count and views:

You May Also Like: How To Send An Email In Python?(Read Here)

Python Web Scraping Code:
from bs4 import BeautifulSoup
import requests

response = requests.get("https://stackoverflow.com/questions/")
soup = BeautifulSoup(response.text, "html.parser")

questions = soup.select(".question-summary")

for question in questions:
    title = question.select_one(".question-hyperlink").getText()
    views = question.select_one(".views").getText()
    vote_count = question.select_one(".vote-count-post").getText()
    print(f"Title: {title}\nViews:{views}\nVote-Count: {vote_count}\n\n")
Title: How to implement mac and dac at beginner to medium level?
Views:
    3 views

Vote-Count: 0


Title: Using AppleScript to control Zoom
Views:
    4 views

Vote-Count: 0


Title: What are difference between calling `connectGatt` on BluetoothDevice vs `connect` on BluetoothGatt
Views:
    5 views

Vote-Count: 0


Title: GroupBy clause removing all null column values
Views:
    7 views

Vote-Count: 0

That’s it for today. It was the basic tutorial for beginners to getting start with BS4 for Web Scraping. We all know that python is one of the leading programming language for doing such kind of work e.g Web Scraping, Automation Etc.

If you found this article useful then please share this with your friends. You can also subscribe our blog via email to get notified with future posts.

Thank’s For Reading…

You may also like

Sending Emails Using Python Script(GUIDE)

Hey Coders, Today’s going to be fun tutorial. Because Today, I’m going to give you A full fledged Guide that How To Send An Email using Python scripts. All the code and modules are explained below that will help you to sending emails using python.

To send an Email in Python, First you need to import some classes to send an email using SMTP servers. Simple Mail Transfer Protocol(SMTP) is basically a communication protocol to transfer electronic mails.

Sending Emails Using Python (Tutorial):

Basically In Python Standard Library, We have a package called “email” that will be help you to send emails using Smtp server through you Python script.

First, We will import this following code in our python file:

from email.mime.multipart import MIMEMultipart

In this above code, We have imported a class called MIMEMultipart from sub-packages of “email” package. Here, Under Email package, we have mime package that stands for Multipurpose Internet Mail Extensions that used to give format to your Emails.

First, Let me show you my code and after then I’ll define each and every line briefly. By the end of this article, You will have full knowledge about sending emails using python.

Python Email Send.py

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText 
import smtplib

message = MIMEMultipart()

message["from"] = "Hulas Karn"
message["to"] = "receivers@gmail.com"
message["subject"] = "Enter Subject of your Email"
message.attach(MIMEText("Type the message that you want to send to user"))

with smtplib.SMTP(host="smtp.gmail.com", port=587) as smtp: 
    smtp.ehlo()  
    smtp.starttls()   
    smtp.login("sender@gmail.com", "password")
    smtp.send_message(message)
    print("You Message Sent")

Now, I’m going to explain each line of code separately.

Line_1: First, We have imported our MIMEMultipart class from email package.

Line_2: Then we have MIMEText class, that will help to attach body of our email.

Line_3: Imported smtplib module, that will help to establish connection with smtp server.

Line_5: Here, we have created an object called message of MIMEMultipart(). In this class, we have some defined headers e.g from, to, subject.

Line_7: Here, we declared a header of message object, where you need to enter Sender Name. To declare this header, you need to define it as message[“from”] = “Your Name Or Sender Name”.

Line_8: After then we need to define message[“to”] = “receiver email address”. In this header, you need to enter receiver’s email address.

Line_9: This header will define subject part of your Email. You need define it as message[“subject”] = “subject of your body”.

Line_10: Here, We don’t have any header to define body of our mail. Therefor, we have a to use attach() function. Under this function, we will use MIMEText() class to define our body of mail. This MIMEText() comes from Line 2, where we have defined sub-package from mime module.

To define body of you email, you need to use this code:

message.attach(MIMEText(“Your Message”))

Line_12: Here, you need to create an object from smtplib class that we had imported at line 3. Because this will help us to establish connection with smtp mail server.

But here, we will be use “with” statement because Once the message would be sent then we need to close our connection. Therefore, instead of creating object separately and closing it, we will use “with” statement.

If you don’t familiar with “with” statement, then you could also create an object of smtp e.g:

SMTP object Without “With” Statement:
smtp = smtplib.SMTP(host="smtp.gmail.com", port=587)
----
----
smtp.close()

But In Line 12, I’ve used “with” statement to create object of smtplib class. In this statement you have to enter two fields – host and port.

Host and port no. will be depend upon the server that you are using. Because, we’re using gmail service therefore host=”smtp.gmail.com” and port=587.

Line_13: Here, We’ve called ehlo() function of smtplib class e.g smtp.ehlo(). It tells the server that we’re client and we want to send an email.

Line_14: smtp.starttls() ensure TLS security for mails, which means Transport Layer Security.

Line_15: smtp.login(“sender_email”,”sender_password”) – In this function, you need to enter two fields, first one Your or Senders email address and password of your email.

Line_16: smtp.send_message(message): In this function, You need to enter MIMEMultipart object that you declared at Line 5.

Line_17: Now, we simply print a message e.g print(“message sent”), which help us to determine that our message sent successfully.

Before sending an email, First, You have to “on less secure apps” from google account security setting. Click Here To On Less Secure app
Less Secure App Access Gmail

Or

If you have Two step verification then you need to create an app password.

Once you’ve done all above process then just run your program and you will be see “Your message sent” on terminal.

Sending emails using python

Now open receivers gmail account and check emails, where you will be see that message sent by Python script.

Email sent by Python Script, Smtplib and email modules

You May Also Like: FULL GUIDE TO BUILD AUTHENTICATION APP IN DJANGO

These were the basic structures to sending emails using Python Language. I hope you guys enjoyed this. Please don’t forget to share this article with your friends and Programmers.

Thank’s To Read…

Processingā€¦
Success! You're on the list.

You may also like

Classes in Python, constructors, Inheritance (Guide)

Classes In Python:

Before Working and creating class in python, Let me give you a short description about Classes in Python. Basically, Classes is a blueprint of any object that you will be create.

Example: Assume, you want to create a String variable object in Python for name field. Then you will be write code something like this:

name = "hulas"

In above code, I’ve created an object called “name” from Python’s inbuilt class called “String“. Now, age can access all those inbuilt method of string class e.g len(), strip(), Etc.

As same like above, We can also create our own custom classes in Python. In which we could define different attributes as a functions. So, that whenever someone would be create an object from our Custom Class, then they will be able to access all those functions declared under that Classes.

Now, Let’s jump into the deep down guide of this Classes in Python.

Creating A Class in Python:

I’m going to explain each and every points through an example, so that you could understand easily.

Let’s create a class name Point, In which we will have different attributes(Functions) to draw different shape. Just like we have different function in String class to perform over string object.

Structure to Create a Class And Object in Python
#Creating Class
Class <class_name>:
      def <function_name>(self):
          ----Operations----

# Creating Object

object_name = class_name()
class_name.funtion_name()  # To Access Function

Now Let’s Create A Class Point and then I will define you each section one by one:

class Point:
    def circle_draw(self):
        print("Draw A Circle")

    def triangle_draw(self):
        print("Draw A Triangle")

    def rectangle_draw(self):
        print("Draw A Rectangle")


point1 = Point()

point1.circle_draw()
point1.triangle_draw()
point1.rectangle_draw()
Ans: 
Draw A Circle
Draw A Triangle
Draw A Rectangle

In this above code, You can see that I’ve created A Class called Point. In this Point Class, I’ve defined 3 functions – circle_draw(), rectangle_draw(), triange_draw(). Then, I’ve created an object name point1 from Point() class.

Now this point1 object could call all methods declared inside that class Point(). You can call these methods by using ‘.’ operator e.g object_name.method_name()

Now Let’s see some advance example, now we will use constructors to initialize objects with initial value.

Note: In Python, We use “self” in each functions as a Parameter. Because all the functions that are declared in Python should have at least one parameter.It’s also a reference to their respective object.

Constructors in Python Classes:

In Python, We also have a constructors that we can use in our class to initialize our objects with initial value.

Let’s suppose, we want to create a object of Point() class with initial values e.g x=1, y=2. Here, we can use constructor to initialize.

Constructors: Constructor is a special method(function) that call It self automatically, Whenever we will create an object.

Let me show you how to create a constructor in Class.

class Point:
      def __init__(self, x, y):
          self.x = x
          self.y = y

In constructor we do use __init__ method to initialize constructors. It’s also known as magic method that we will discuss in other article. For Now, Only remember that __init__ function we’ve used here to declare constructor inside a class.

Under __init__ function, we’ve declared two variables x and y. Because these value we want to invoke initially whenever someone will be create an object.

After then we used self.x and self.y to reference x and y variable of objects. Now you can also access these x and y data by using same “.” dot operator e.g: object_name.variable_name

class Point:
      def __init__(self, x, y):
          self.x = x
          self.y = y
       
      def draw(self):
          print(f"Point ({self.x}, {self.y})")

point_1 = Point(1,2)
point_1.draw()
Ans:
Point (1, 2)

In above code, You could see that I’ve initialized point_1 object by value 1 and 2. Now then I’ve called a method draw by using dot operator.

You can also create variables separately in program apart from constructors Like:

point_1.z = 3

You May Also Like: Python Django Playlist For Web Development(Read Here)

Inheritance in Classes

In Python, One class can inherit features of other Classes. It’s the one of the most important feature of objected oriented type of Programming languages.

Inheritance: In Inheritance, You can inherit all the methods of Parent class into Child class. So, that you don’t need to rewrite a same code in different classes.

You could inherit method of one class to another by using inheritance. Let me show this through an example:

Let’s create classes for different animals like:

Classes in Python, Inheritance and Constructors

Let’s create 3 different classes

  • Animal()
  • Dog()
  • Fish()

In Animal, we will define only one function e.g Eat(). Because we know that all types of animals eats something. After then we will define Walk() function, because all dogs walk and eat also.

As similar a fish can have also two functions like Swim() and Eat().

But here, we’ve noticed that Eat() function are common in each classes. Because any kind of animals ca eat. Therefore, instead of defining Eat() function in each classes simply we will inherit it from Animal class. Because Animal class has already had Eat() function defined.

Now, Here Animal class will be Parent or Base class. After Then the classes who inherited Eat() function from Animal will be know as Child Or Sub Classes.

To Inherit class You need follow format like this :

class Animal():
    def eat(self):
        print("Eat")  # Each type of Animal should eat

class Dog(Animal):  # Here We Inherited Eat Method of Animal by using Inheritance
    def walk(self):
        print("walk")

class Fish(Animal):
    def swim(self):
        print("swim")

dog = Dog()  
fish = Fish()

dog.eat()  
dog.walk()
 
fish.swim()
fish.eat()  
result: 

Eat
walk
swim
Eat

In the above code you could see that all child classes inherited base class Animal. To inherit any class in Python you use this syntax:

class child_class(base_class)

Same I used Animal as Base class and Fish and Dog as A child. Now fish and dog class can inherit Animal Eat() Function easily. You could access all methods of Animal class by using same dot operator.

I hope you all will like this article. Please share this with your friends and geeks. You can also follow or subscribe our blog via email to get notified with next update of future posts.

Thank’s To Read…

You may also like

Django Models Relationship – OneToMany, ManyToOne

Hey developers, Today I’m going to explain one of the confusing topic in Django. We’re going to discuss Django Models Relationship e.g OneToMany and ManyToMany. These are two basics relationship in Django database that are found quite confusing to beginners.

So, I’m going to explain both of these two relationship one by one with an Example.

Django Models Relationship

First, Let me show you my Models.py Code where I’ve shown both of these relationships among different models.

models.py
from django.db import models

# Category Model
class Category(models.Model):
    name = models.CharField(max_length=20)

    def __str__(self):
        return self.name

# BlogPost Model
class Post(models.Model):
    title = models.CharField(max_length=255)
    body = models.TextField()
    created_on = models.DateTimeField(auto_now_add=True)
    last_modified = models.DateTimeField(auto_now=True)
    categories = models.ManyToManyField('Category', related_name="posts")

    def __str__(self):
        return self.title

#  Comment Model
class Comment(models.Model):
    author = models.CharField(max_length=60)
    body = models.TextField()
    created_on = models.DateTimeField(auto_now_add=True)
    post = models.ForeignKey('Post', on_delete=models.CASCADE)

In the above models.py, I’ve created different models for A Fully Functional blog. Where you could see three different models e.g Post, Category and Comment. Now Let’s start our Django Models Relationship Guide.

So, First we will talk about ManyToMany Django Database Realationship.

Django ManyToMany Model Relationship:

Django Many To Many Relationship, Foreign Key, Etc.

In this ManyToMany Relationship, We can have models that could be related to more than one posts. This models will be not lies under any particular models.

Example:

Let’s Suppose we’ve created 3 Post With the Title as given below:

  1. Post_1: How To Improve Coding Skills
  2. Post_2: Top 10 Modules in Python
  3. Post_3: Django Full Guide For Beginner.

Now, We have also 3 different Categories from Category Modules:

  1. Programming
  2. Python
  3. Django

Now, here you could see that Post_1 will belongs to only 1 categories(Programming). Where Post_2 will be also belongs to First two categories(Programming, Python) and Finally Post_3 will have all these categories(Programming, Python and Django).

Here, You can see that either a post or categories is not just limited to single post or categories. Which means In ManyToMany Django Relationship, “A single Post can have different categories and as same as A categories could be belongs to different posts”

In the above “models.py“, You can see in the Post Model that I’ve defined categories by using ManyToMany field. You can define ManyToMany field by using following code:

categories = models.ManyToManyField(‘Category’, related_name=”posts”)

Here, I’ve filled ‘Category’ Model in place of class that I want related with the Post Model.

You May Also Like: How To Add Bootstrap 4 Form in Django with crispy-forms

Django OneToMany Model Relationship:

Django Models Relationship - OneToMany

In this this Relationship An Object of a model will be related to only Single Model Object. Which means Like A model can have different objects from other models. But A Child model couldn’t belongs to other Model. That Child model will be related to only a single model.

For Example:

In ManyToMany, Post could have different categories and A categories could belongs to different Post Model.

But Here, A Post Model can have different Comments like, Comment_1, Comment_2, Comment_3. But Here, these comments will be not related to other posts like Post_2 and Etc. As a result whenever someone would be delete Post_1, then all these comments related to Post_1 would be deleted.

It’s also help to design database for specific users, So that each user will have their own database to store information.

In the above Models.py code, I’ve defined that how you could make OneToMany Relationship among Models.

Here, You’ll need to use Foreign Key field into main Child Class Model to connect it with Parent class model.

post = models.ForeignKey('Post', on_delete=models.CASCADE)

You need to add above code in Comment model. After than any created comment would be belongs to only specific Post Model Object.

Here, You can see that I’ve filled two parameters – First I filled ‘Post’ that refers comment would be related to only one Post. Second we have on_delete=models.CASCADE, Which means whenever you will delete any Post then all the comments related to that specific Post will be automatically delete.

Short Explanation:

OneToMany Relationship: In this relationship, A model can have different Child models but all those child model will be related to only this particular model.

ManyToMany Relationship: In this relationship, Both of the model could be related to each others. Example: Post And Comments.

I hope you all will be like this article. Please don’t forget to share this article with your friends and geeks. You can also bookmark or follow our blog for such kind of programming updates.

Thank’s To Visit…

You may also like

Django Authentication Page Build- Login, SignUp(GUIDE)

How to build Authentication Form in Django

Hey Coders, Today we’re going to build a full authentication functionality in Python Django Framework. Here, We will be use Django built in Forms e.g: UserCreationForm, AuthenticationForm, Etc. In other, we will be use some bootstrap to design our NavBar.

Description:

In this tutorial, We will be design 4 functionality e.g: home, login, signup and logout. Whenever user will be logged in then navbar will be show 2 Button – 1. Home and 2. Logout. In Other hand, If user will be logged out then we will be navbar with 3 Button – 1. Home, 2. Login, 3. SignUp.

So basically, our navbar will be change upon the user authenticated or not. With that said Let’s start our Authentication project. To Build Django Authentication Page Follow given steps.

Django Authentication Page – Login, SignUp:

Let’s first create our django project with the project name “security”. Types Following command to create:

django-admin startproject security

Now It’s time to create an app called “customer” within our project. So, first get inside your project folder then type:

python manage.py startapp customer

Now List this “customer” app inside your INSTALLED_APPS of settings.py file, like this:

settings.py

INSTALLED_APPS = [
    '----',
    '----',
    '----',
    'customer',
]

Because we will be using our templates in project root folder, therefore we need to set path of our templates

settings.py

TEMPLATES = [
          {   
              -------------------------------,
              'DIRS': [os.path.join(BASE_DIR, 'templates')],
              -------------------,
         }
]

Now create your templates folder inside you project root. Now Inside this folder we will be create our all required Html files.

Before moving forward, run your migrations and migrate by using following command:

python manage.py makemigrations
python manage.py migrate

Now It’s time to connect your root urls.py to your customer app urls.py. But before that create a urls.py file inside your customer app folder.

Now open your root urls.py file and add following code:

security/urls.py
from django.contrib import admin
from django.urls import path, include   # Add this one

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('customer.urls')),   # add this one
]

Now Open your customer/urls.py and setup url patterns like this:

customer/urls.py
from django.urls import path
from . import views

urlpatterns = [
    # Add Urls
]

In above code, Now whenever we will be add any url then we will add it under urlpatterns here like:

path('pathname/', views.function_name, name="pathname"),

Now Let’s create our homepage first.

Homepage Django(NavBar Change):

But before create views and urls, firstly we need to create our “base.html” file. Afterwards, all other html file would be inherit base.html file.

Base.html(Before Modify)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Security</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
</head>
<body>

<!--Navbar-->

<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
  <a class="navbar-brand" href="#">Navbar</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse" id="navbarNav">
    <ul class="navbar-nav">
      <li class="nav-item active">
        <a class="nav-link" href="{% url 'home' %}">Home</a>
      </li>
    </ul>
    <ul class="navbar-nav ml-auto">
      <li class="nav-item">
        <a role="button" class="btn btn-primary" href="{% url 'loginuser' %}">Sign In</a>
      </li>
      Ā 
      <li class="nav-item">
        <a role="button" class="btn btn-warning" href="{% url 'signupuser' %}">Sign Up</a>
      </li>
    </ul>
  </div>
</nav>

{% block content %}

{% endblock %}

</body>
</html>

Now above code is not yet ready for change dynamically on the basis of user authenticated or not. Because we’re not added any conditions yet. We will be implement conditions later on after completing our signup and login form. For then, all other html files will be inherit above base.html file.

Now let’s create “home.html” file and then inherit above base.html file. Because I’ve added Bootstrap 4.5 CDN into above code therefore home.html will be also inherit that bootstrap cdn. We don’t need to define it here separately.

home.html(Before Modify)
{% extends 'base.html' %}

{% block content %}

<div class="container">
    <h1 class="alert alert-danger">USER IS LOGGED OUT</h1>
</div>

{% endblock %}

You can see that above home.html file inherit base.html file by using {% extends ‘base.html’ %}. But still there is something missing that we will be add later on. I’ve not added any condition yet because before declaring any signup and login, then it show error.

Now let’s setup our views.py file of our customer app:

customer/views.py
from django.shortcuts import render, redirect

def home(request):
    return render(request, 'home.html')

In above code, You can see that I’ve created a function called home and imported some function. In this function, I’ve returned a home.html page. Now It’s time to create a path link into the customer/urls.py.

customer/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name="home"),
]

In this above code, I’ve created a blank path which means whenever someone would visit our website then they will this page at homepage. After then I called my function “home” from views.py and then finally give it to name of “home”. So, that whenever I would like to call it in future then I don’t need to remember their full path.

Now run your server and you will see your homepage now.

Logout User in Django

But It’s not yet ready because we didn’t yet define any major functions like Signup, Login, Logout and Conditions.

Let’s first create our Sign Up form via using in built Forms of Django 3.

Sign Up Page in Django:

In Django, we have inbuilt forms and modules that makes our tasks so easy. We don’t need to explicitly define each function.

In case of forms, we have two major inbuilt form in Django. First one is “UserCreationForm()” for Signup functionality and second one is “AuthenticationForm()” for Log In functionality. We will also use some inbuilt models like User to create an user and functions.

First, Let’s add and import required modules and packages under “customer/views.py

customer/views.py
from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm  # Add This one
from django.contrib.auth.models import User
from django.contrib.auth import logout, login, authenticate


def home(request):
    return render(request, 'home.html')

# Add this one For Signup
def signupuser(request):
    if request.method == 'GET':
        return render(request, 'signup.html', {'form': UserCreationForm()})
    else:
        if request.POST['password1'] == request.POST['password2']:
            user = User.objects.create_user(username=request.POST['username'],
                                            password=request.POST['password1'])
            user.save()
            login(request, user)
            return redirect('home')
        else:
            return render(request, 'signup.html', {'form': UserCreationForm(), 'error': 'password did not match'})

Now, In this above code I also defined some signupuser function.

signupuser function says that whenever someone will be access our website then he will redirected to our signup.html page, that we will create later on. Here, we will be use dictionary to call UserCreationForm(). By using dictionary we can call this form into signup.html page by using {{form}}.

If someone will process request of POST to register their self by clicking submit button. Then it will first check the condition that both the entered password are same or not. If it’s same then It will create a User with the given user name and password. After then it will save it in database and log In it to the current user. Then It will successfully return it to the homepage.

Else It will return same page with some error e.g password did not match.

Now add path of sign up into urlpatterns of “customer/urls.py”:

customer/urls.py
path('signup/', views.signupuser, name="signupuser"),

Add above code right after home path into your urls.py. Now create a signup.html file that we will return to user whenever someone would access our signup url.

signup.html
{% extends 'base.html' %}

{% block content %}

<h1>Sign Up</h1>
<hr>

<form method="post">
    {% csrf_token %}
    <strong>{{error}}</strong><br>
    {{form}}
    <button type="submit" class="btn btn-primary">Sign Up</button>
</form>
{% endblock %}

In this above code, you can see that I’ve created a form with post method. Here, you could see that I used {{form}} to access UserCreationForm() and {{error}} to call error.

Modifications – Home, Base HTML

Now along with that lets modify our home.html and base.html. In these files we will add some condition that will check conditions and then they will change their content according to that condition.

Here, we will check that If an user is authenticated then It will show other navbar and else it will show other navbar.

In home.html, If the use will be authenticated then it will show the message e.g “User is Logged In ” and else It will show message e.g “User is logged out”.

Home.html(Modified)
{% extends 'base.html' %}

{% block content %}

<!--IF user is logged in-->
{% if user.is_authenticated %}

<div class="container">
    <h1 class="alert alert-primary">USER IS LOGGED IN</h1>
</div>

{% else %}

<div class="container">
    <h1 class="alert alert-danger">USER IS LOGGED OUT</h1>
</div>

{% endif %}

{% endblock %}

In above code, You could see that we’ve implemented a If-Else conditions e.g: {% if user.is_authenticated %} show content 1 {% else %} Show content 2 {% endif %}.

Similarly, we will add same If-else condition in base.html too.

Base.html(Modified)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Security</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
</head>
<body>

<!--Navbar-->

{% if user.is_authenticated %}

<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
  <a class="navbar-brand" href="#">Navbar</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse" id="navbarNav">
    <ul class="navbar-nav">
      <li class="nav-item active">
        <a class="nav-link" href="{% url 'home' %}">Home</a>
      </li>
    </ul>
    <ul class="navbar-nav ml-auto">
      <form action="{% url 'logoutuser' %}" method="POST">
        {% csrf_token %}
        <button type="submit" class="btn btn-danger">Log Out</button> 
      </form>
    </ul>
  </div>
</nav>

{% else %}

<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
  <a class="navbar-brand" href="#">Navbar</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse" id="navbarNav">
    <ul class="navbar-nav">
      <li class="nav-item active">
        <a class="nav-link" href="{% url 'home' %}">Home</a>
      </li>
    </ul>
    <ul class="navbar-nav ml-auto">
      <li class="nav-item">
        <a role="button" class="btn btn-primary" href="{% url 'loginuser' %}">Sign In</a>
      </li>
       
      <li class="nav-item">
        <a role="button" class="btn btn-warning" href="{% url 'signupuser' %}">Sign Up</a>
      </li>
    </ul>
  </div>
</nav>


{% block content %}

{% endblock %}

</body>
</html>

Now In above code, You can see that If user.is_authenticated then it will return navbar(home, logout) and else It would return navbar(home, signup, login).

Sign In Django Authentication Page:

Now Let’s create our Sign In page in Django. As I told you In Django, we have AuthenticationForm() and authenticate functions to verify and authenticate user. So, that we could logged them into the server without allowing any unauthorized access.

Let’s first create our function in “customer/views.py” and add following code right after signupuser function.

customer/views.py:
def loginuser(request):
    if request.method == 'GET':
        return render(request, 'login.html', {'form': AuthenticationForm()})
    else:
        user = authenticate(request, username=request.POST['username'], password=request.POST['password'])
        if user is None:
            return render(request, 'login.html',
                          {'form': AuthenticationForm(), 'error': 'Password Or Username incorrect'})
        else:
            login(request, user)
            return redirect('home')

In above code, You could see that If we would get server request from user then we will return a login.html file. In which, we will able to access AuthenticationForm() using our defined dictionary key e.g {‘form’: AuthenticationForm()}.

Else If the user request a post then first we will be authenticate user identity with given username and password. If the user would not exist in our database then we will simply return a error else we will be logged them into the server and redirect them to homepage.

Now let’s create our login.html, I’ve created a following login.html file that you could copy and paste.

login.html
{% extends 'base.html' %}

{% block content %}

<h1>Sign In</h1>
<hr>

<form method="post">
    {% csrf_token %}
    <strong>{{error}}</strong><br>
    {{form.as_p}}
    <button type="submit" class="btn btn-primary">Sign In</button>
</form>
{% endblock %}

Now, Let’s setup our url path for Login page. You need to add following code right after signup path

customer/urls.py
 path('login/', views.loginuser, name="loginuser"),

Log Out Django Page:

It’s our final task, In which we will create a logout functionality. Here, we need to define a function for logout and then need to map url for logout. Here, we don’t need to create any logout html page separately.

Let’s first define our logoutuser function in views.py. Add following code right after that loginuser function

customer/views.py
def logoutuser(request):
    if request.method == 'POST':
        logout(request)
        return redirect('home')

Here, we will have only post method. Because we want whenever someone would click on Sign Out button only then It should have process a functionality.

Now We need to add logout url in customer/urls.py. we will be add following code right after that login url.

customer/urls.py
path('logout/', views.logoutuser, name="logoutuser"),

Now, we’ve already added a signout function in base.html that you could see. So, we don’t need it to define it again.

code for logout in base.html
<form action="{% url 'logoutuser' %}" method="POST">
    {% csrf_token %}
    <button type="submit" class="btn btn-danger">Log Out</button> 
</form>

Now It’s all done, let’s see how it would be look like too see each and every pages. But before that run your server via using “python manage.py runserver”.

1. Homepage And Without Login:
Django Authentication Page
2. Homepage and Navbar With Logged In
Authentication Page in Django Web App
3. Sign Up Page
UserCreationForm - Sign Up Form In Django
4. Login Page
AuthenticationForm() in Django For Login

Now these are the above front-end that you will be going see whenever you run your server. So, Let’s end this tutorial. If you would still face any problem then you can just see all those code in give github repositiry:

GitHub Repository:
GitHub Link

Or

In Shell type “git clone https://github.com/hk2lite/security.git”

You Can Also customize your form and bootstrap with Django-Crispy-Forms Module. Click the link given below to see how to use it:

Link: How To Add Bootstrap4 in Django With crispy-forms

So, I hope you all would like this article. If yes then please don’t forget to share this everywhere you could. You could also subscribe our blog via email to get notified with future posts.

Thank’s To Visit…

You may also like

How To Add Bootstrap 4 with Django Crispy Forms

Hi Coders, Today, I’m going to give you full tutorial about “django-crispy_forms”. It will help you to customize your django-forms with Bootstrap 4 themes. Here, you don’t need to define or write bootstrap code explicitly to customize your django forms.

Here, I’ll give you full tutorial that how you could install crispy-forms and use it in your django forms. Please read full article carefully till the end.

Installation

First of you all have to install package called “django-crispy-forms” by using pip:

pip install django-crispy-forms

Once you’ve installed this above package then you need to add this inside your INSTALLED_APPS of Settings.py file.

settings.py:
INSTALLED_APPS = [
    '...'
    '...'
    .
    .
    'crispy_forms',   # Add This
]

CRISPY_TEMPLATE_PACK = 'bootstrap4'  # Add This
Django Form Creation

Now Firstly, Let’s create A django form, so that we can use our django-crsipy-forms over that. I’m going to derive a django form from my existing model

models.py:
from django.db import models
from django.contrib.auth.models import AbstractUser

class CustomUser(AbstractUser):
    gender_type = (
        ('male', 'male'),
        ('female', 'female'),
        ('others', 'others'),
    )
    address = models.TextField()
    gender = models.CharField(default=1, choices=gender_type, max_length=15)

Now let’s create our custom form in forms.py. I’ve written following code to create a form:

forms.py:
from django import forms
from .models import CustomUser
from django.contrib.auth.forms import UserCreationForm

class RegisterationForm(UserCreationForm):
    class Meta:
        model = CustomUser
        fields = ['username', 'address', 'password1', 'password2']

Now You need to setup your Bootstrap4 inside you html file. Because I’m driving ‘singup.html’ from ‘base.html’. I’ll add Bootstrap4 CDN inside my base.html file.

Bootstrap CDN:
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
This is my ‘base.html’
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
    <title>Registeration</title>
  </head>
  <body>
    <div class="container">
      <div class="row justify-content-center">
        <div class="col-8">
          <h1 class="mt-2">Sign Up</h1>
          <hr class="mt-0 mb-4">
          {% block content %}
          {% endblock %}
        </div>
      </div>
    </div>
  </body>
</html>

Now Let’s create our views.py file to save current call and save form:

views.py
from django.shortcuts import render, redirect, get_object_or_404
from .froms import *
from .models import *
from django.contrib.auth import login, logout, authenticate

def register(request):
    form = RegisterationForm()
    if request.method == 'POST':
        if request.POST['password1'] == request.POST['password2']:
            customer = CustomUser.objects.create_user(username=request.POST['username'],
                                                      password=request.POST['password1'],
                                                      address=request.POST['address'])
            customer.save()
            login(request, customer)
            return redirect('home')

    return render(request, 'customer/register.html', {'form': form})

Now let’s create our urls.py file, where we can see our website live.

urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('register/', views.register, name="register"),
]

Now, we will create our register.html file and extend this html file from base.html. So, that we can access our Bootstrap feature.

register.html
{% extends 'base.html' %}

{% block content %}
  <form method="post">
    {% csrf_token %}
    {{ form }}
    <button type="submit" class="btn btn-success">Register</button>
  </form>
{% endblock %}

In above code of register.html, we didn’t use yet any crispy-form code. Let’s see how It would be look like now:

How To create Forms in Python django

So, You can see that It’s looks so ugly right now. Now, It’s time to add our “django-crispy-forms” tags. So, To use django-crispy forms, First you need to add following code before {% block content %}:

{% load crispy_forms_tags %}

After adding above tags then you need to use {{form|crispy}} instead of using just {{form}}

{% extends 'customer/base.html' %}

{% load crispy_forms_tags %}

{% block content %}
  <form method="post">
    {% csrf_token %}
    {{ form|crispy }}
    <button type="submit" class="btn btn-success">Register</button>
  </form>
{% endblock %}

Now you can see that your forms becomes so attractive and prettier than previous one. Because {{form|crispy}} tag added all those default bootstrap tags into your form automatically.

How To Use bootstrap4 by using Django-crispy-forms in you django app

You can also add this tag {{ form.name|as_crispy_field }} to customize your each fields more beautifully.

{% extends 'customer/base.html' %}

{% load crispy_forms_tags %}

{% block content %}
  <form method="post">
    {% csrf_token %}
    <div class="row">
      <div class="col-6">
        {{ form.first_name|as_crispy_field }}
      </div>
      <div class="col-6">
        {{ form.last_name|as_crispy_field }}
      </div>
    </div>
    {{ form.email|as_crispy_field }}
    {{ form.address|as_crispy_field }}
    <button type="submit" class="btn btn-success">register</button>
  </form>

{% endblock %}

Now, You can see that applied row class has been applied over our form.

use crispy forms to add bootstrap in you django forms

So, I hope you all would like this article about how to add bootstrap with you django-forms. It’s our full tutorial about django-crispy-forms.

You May Also Like : How To Deploy Django App To Heroku Server(Free)

If you are a passionate developer or blogger then don’t forget to subscribe our blog via email.

Thank’s For Reading…

You may also like