How to build a User Registration(Login/Signup/Logout) System in Django

1. Introduction


In this post, we are going to see how to build a User registration system in Django using the auth module in Django. The example will cover steps to build your registration system where users can register(signup)/login using the credentials and logout of the system.



Let's get Started! 

2. Starting a new Project 

If you are new to Django, please make sure to check out the steps to create a virtual envt in python before creating a Django project. If you already have one you can continue to follow along with me.

Step #1 : Create a Django project

We are not going to use any database-model for this tutorial, we will cover soon in some other post. Let's create a new Django project by running the below command inside your virtual env.

 django-admin startproject mysite

Step #2: Create a Django app

In this tutorial, we’ll create our accounts app in the same directory as your manage.py file so that it can be imported as its own top-level module, rather than a submodule of mysite.

To create your app, make sure you’re in the same directory as manage.py and type this command:

python manage.py startapp accounts

Once done you should be able to see a below folder structure with the below files.

Step #3: Update your Setting.py


Make sure to update your setting.py with a new app so that it can be picked up while running the server.

INSTALLED_APPS = [

    'accounts.apps.AccountsConfig',
	
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

3. Building your Base template for homepage/signup page/login page/login

First, we are going to build a base template for our homepage using Bootstrap. Navigate to mysite ((app) inside the main mysite project). create a template folder and add a file called base.html

You can paste the below code inside base.html .This will be a basic template which we are going to use in our project.


<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="">
  <meta name="author" content="">


  <title>NintyZero</title>

  <!-- Bootstrap core CSS -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

</head>

<body>

  <header>
    <nav class="navbar navbar-expand-lg navbar-light bg-light">
      <a class="navbar-brand" href="">NintyZero</a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
      </div>
    </nav>
  </header>
  <div class="container">
      {% block content %}
      {% endblock %}
  </div>

  <footer class="text-muted">
    <div class="container text-center">
      <p>This is a footer {% now "Y" %}</p>
      </div>
  </footer>

  <!-- Bootstrap core JavaScript
  ================================================== -->
  <!-- Placed at the end of the document so the pages load faster -->
  <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</body>
</html>

</code></pre>

4.Updating the URL for navigation 

To update the URL pattern (for ex we want to show login page once user reaches account/login or account/signup. we can do that by adding the URL pattern in urls.py file(if not found create one) inside your mysite folder and add the below code.

from django.contrib import admin
from django.urls import path,include
from products import views


urlpatterns = [
    path('admin/', admin.site.urls),
    path('',views.home,name="home"),
    path('accounts/',include ('accounts.urls')),
]


5.Adding view for Login/Signup/Logout

Create a template/account folder inside account app and add two Html files named login.html and signup.html

Use the below code to create a Signup Page


{% extends 'base.html' %}

{% block content %}


{% if error %}
{{ error }}

<br/>
<br/>
{% endif %}

<h1>Signup!</h1>

<form method = "POST" action="{% url 'signup' %}">
    {% csrf_token %}
    username:
    <br/>
    <input type="text" name="username" />
    <br/>
    Password:
    <br/>
    <input type="password" name="password1" />
    <br/>
    confirm Password:
    <br/>
    <input type="password" name="password2" />
    <br/>
    <input class ="btn btn-primary" type="submit" value= "signup" />
    <br/>



</form>


{% endblock %}
Login.html

{% extends 'base.html' %}

{% block content %}


{% if error %}
{{ error }}

<br/>
<br/>
{% endif %}

<h1>Login!</h1>

<form method = "POST" action="{% url 'login' %}">
    {% csrf_token %}
    username:
    <br/>
    <input type="text" name="username" />
    <br/>
    Password:
    <br/>
    <input type="password" name="password" />
    <br/>
    <input class ="btn btn-primary" type="submit" value= "Login" />
    <br/>



</form>


{% endblock %}

6. Adding the logic for login and signup

Open the view.py (create one if now found) inside accounts app folder and add the below code to it.

from django.shortcuts import render,redirect
from django.contrib.auth.models import User
from django.contrib import auth

def signup(request):
    if request.method == "POST":
        if request.POST['password1'] == request.POST['password2']:
            try:
                User.objects.get(username = request.POST['username'])
                return render (request,'accounts/signup.html', {'error':'Username is already taken!'})
            except User.DoesNotExist:
                user = User.objects.create_user(request.POST['username'],password=request.POST['password1'])
                auth.login(request,user)
                return redirect('home')
        else:
            return render (request,'accounts/signup.html', {'error':'Password does not match!'})
    else:
        return render(request,'accounts/signup.html')

def login(request):
    if request.method == 'POST':
        user = auth.authenticate(username=request.POST['username'],password = request.POST['password'])
        if user is not None:
            auth.login(request,user)
            return redirect('home')
        else:
            return render (request,'accounts/login.html', {'error':'Username or password is incorrect!'})
    else:
        return render(request,'accounts/login.html')

def logout(request):
    if request.method == 'POST':
        auth.logout(request)
    return redirect('home')


Conclusion:

In this post, we learned how to build a user login and signup systems. we also saw how to build views and use it to register and log in.

Getting Started with Django Quickly [Step by Step tutorial]

1. Introduction:


In this post, we are going to see an overview of Django (as a tutorial) and setting up the environment to get started with building WebApps or Rest APIs.

Before we start setting up the environment we can have a look into the features Django brings to help with development.


YouTube-Style Face Detect - Crop and Blur using python and OpenCV

This post will focus on the core concepts in image processing. These areas will act as the building blocks for more intricate image manipulations in a later post. Becoming familiar with these characteristics of using Python and OpenCV, we will then be able to jump around to the different concepts more easily. 

Face processing is a hot topic in artificial intelligence because a lot of information can be automatically extracted from faces using computer vision algorithms. 

The face plays an important role in visual communication because a great deal of non-verbal information, such as identity, intent, and emotion, can be extracted from human faces.

Face processing is a really interesting topic for computer vision learners because it touches on different areas of expertise, such as object detection, image processing, and landmark detection or object tracking.




A Simple Explanation of Regularization in Machine Learning

In this post, we are going to look into regularization and also implement it from scratch in python (Part02). We will see with example and nice visuals to understand it in a much better way. We already know about the Linear regression where this is used.


In-depth Explained Simple Linear Regression from Scratch - Part 1

In my opinion, most Machine Learning tutorials aren’t beginner-friendly enough. It very math-heavy or it doesn't help you with the algorithms behind it.
In this post, we are going to do the simple Linear Regression from scratch. We will see the mathematical intuition behind it and we write the code from scratch + test it and I'm super excited to get started!!




Overview Guide To Tensorflow 2.x with Examples


The most concise and complete explanation of what TensorFlow is can be found at (https://www.tensorflow.org/) and it highlights every important part of the library.

TensorFlow is an open-source software library for high-performance numerical computation.

Its flexible architecture allows easy deployment of computation across a range of platforms (CPUs, GPUs, and TPUs), from desktops to clusters of servers, to mobile and edge devices.

Originally developed by researchers and engineers from the Google Brain team within Google's AI organization, it comes with strong support for machine learning and deep learning,and therefore the flexible numerical computation core is employed across many other scientific domains.

In this blog post, we are going to see the basics for TensorFlow 2.x. This can be used as getting started guide to learn and understand it.

I'm not going to cover the installation/Setup of the Jupyter part as this can be found online easily.




Create a CRUD Restful Service API using Flask + Mysql [in 7 minutes!]

In this article, we will learn how to build Simple Restful API with flask and Mysql that have capabilities to create, read, update, and delete data from the database.

Flask being a microframework provides the flexibility of the data source for applications and also provides library support for interacting with different kinds of data sources. There are libraries to connect to SQL- and NoSQL-based databases in Flask.


Error and Exception Handling using Try/catch in powershell



One of the most important components for creating PowerShell scripts is error and exception handling.

I've personally made mistakes while writing scripts without proper exceptions and trying to figure out why it got terminated.๐Ÿ˜ต 

Error and exception handling is often a forgotten component of scripting because it's common to feel that the code should always execute linearly and in an implicit fashion.





This is due to the common practice of taking the small scripts and using them as starting points for more complex scripts. 

The more complex you build your scripts, the higher the probability of failure ๐Ÿ  and unexpected results.



In this post, you will learn the following:
  • Types of error
  • Different ways to handle Exceptions
  • Error and exception handling with parameters
    • Different Actions
  • Error and exception handling with Try/Catch


PowerShell has two different types of errors which are terminating and non-terminating.

Terminating errors will stop the script from executing further commands. 

The non-terminating errors will call the write-error cmdlet, print an error to the screen, and continue.


Error and Exception Handling 

PowerShell offers several different options to achieve error and exception handling.

The most popular method used to catch non-terminating errors is bypassing the error and exception handling parameters while executing PowerShell cmdlets. 

You can then call the error variable and execute other actions based on the contents of the $error variable.


The PowerShell parameters that handle error and exceptions are -WarningAction and ErrorAction

When an issue occurs with your script, the PowerShell CLR will reference the -ErrorAction and -WarningAction arguments to determine what the next step for the script is.


There are five actions that are supported within PowerShell. 

  • The SilentlyContinue action will suppress the error and warning information, populate the error variables, and continue.
  • The Ignore action will suppress the warning and error message and not populate any specified variables.
  • The Continue action will write to the screen the warning and error information and attempt to continue with the script.
  • The Stop action will write the warning and error information stop the execution of the script.
  •  The Inquire action will prompt the end-user if they want to HaltSuspendAccept the Error, or Accept All Errors.


By default, PowerShell is set to Continue, however, you can set the $errorActionPreference and $warningActionPreference (Global variables) to different values for different default actions.


We will see one example of cmdlet error handling.


Function TestExample($tesparam) { 
Get-service $tesparam –ErrorAction SilentlyContinue –ErrorVariable err

    If ($err) {
      Write-host "Error! Error Details: $err"
        return
    }
  
    Write-host "Successfully Retrieved Service Information for $svcName. "
}
TestExample "Windows Update"
Write-host "" 
TestExample "Does Not Exist"

####################################################
Status   Name               DisplayName                           
------   ----               -----------                           
Stopped  wuauserv           Windows Update                        
Successfully Retrieved Service Information for . 

Error! Error Details: Cannot find any service with service name 'Does Not Exist'.


If the $err variable has data in it or is implied true, the script will write to the console Error! Error Details: $err followed by return, which will exit out of the function. If the $err variable doesn't have any error details, it will proceed to write to the console.


Handling error with try/Catch/Finally

One of the more popular error and exception handling techniques is leveraging Try/Catch methodology.

The Try/Catch block is used for handling terminating errors and has a very simple structure. You first use the Try { } section of code and then use Catch { } to catch any errors and perform actions based on the errors.



try
{
    $items = Get-Item -Path C:\Does\Not\Exist, C:\Windows, $env:APPDATA -ErrorAction Stop
}
catch [System.Management.Automation.ItemNotFoundException]
{
    # Specific catch block for the exception type
    # PSItem contains the error record, and TargetObject may contain the actual object raising the error
    Write-Host ('Could not find folder {0}' -f $PSItem.TargetObject)
}
finally
{
    # Regardless of whether an error occurred or not, the optional
    # finally block is always executed.
    Write-Host 'Always executed'
}

You can find out which type of exception occurred by examining its type, using $Error[0].Exception.GetType().FullName.



One of the best practice techniques for error and exception handling is to combine the use of the Try/Catch block and cmdlet parameters. This is due to PowerShell being able to gracefully handle terminating and non-terminating error scenarios. 


For instance, if you execute a line of code that throws a warning message but doesn't generate a terminating error, you can catch the warning and perform actions based on that warning.



Try {
    Get-process "Doesn't Exist" –ErrorAction SilentlyContinue     –ErrorVariable err
}
Catch {
  Write-host "Try/Catch Exception Details: $_"
}
if ($err) {
  Write-host "Cmdlet Error Handling Error Details: $err"
}

#############################################
Cmdlet Error Handling Error Details: Cannot find a process with the name "Doesn't Exist". Verify the process name and call the cmdlet again. 



When you execute the script, you see that the Catch method doesn't catch the error message from the get-service  the cmdlet. This is due to the error being a non-terminating error, and so it doesn't invoke the block


When you run the script, however, the cmdlet properly handles the error and places the error details in the $err variable. 

Quick Summary: 
  • There are two types of errors in PowerShell: terminating and nonterminating.
  • Error records are written directly to the default output.
  • Error records are rich objects.
  • The $error variable stores the last 256 errors (by default).
  • You can specify a specific variable for errors by using the -ErrorVariable parameter.
  • $? stores a Boolean value indicating the execution status of the last command.
  • $ErrorActionPreference and the -ErrorAction parameter can be used to control the action taken if an error occurs.
  • Terminating errors and exceptions can be managed by the trap statement or the try/catch/finally statements (preferred).
Happy Coding!


Working with XML Files in Powershell [Parsing]


In the last post, we worked with CSV types of files. The next type of file we're going to look at is Extensible markup language(XML). They are used for various reasons, for example, storing properties data that can be used for configuration and data storage.





XML is one of the basic file extensions and consists of opening and closing tags..



<config>
 <pctype>
        <type name="Desktop PC" value="D"></type>
        <type name="Notebook" value="N"></type>
        <type name="Tablet PC" value="T"></type>
    </pctype>
    <logdir>E:Logs</logdir>
    <logfile>SCCMLogs.txt</logfile>
</config>

Parameters can be added both in a nested fashion and inline. By using the nested approach, you will also have a visual recognition of which objects are on the same level through indentation:


We will start with an example of storing and loading configuration data๐Ÿ’—




PS C:\WINDOWS\system32> $XMlcontent= @'
<config>
 <pctype>
        <type name="Desktop PC" value="D"></type>
        <type name="Notebook" value="N"></type>
        <type name="Tablet PC" value="T"></type>
    </pctype>
    <logdir>E:Logs</logdir>
    <logfile>SCCMLogs.txt</logfile>
</config>
'@


Now let's try to save the file and then read the content of the XML file as an XML object. To do this we perform the following steps.



PS C:\WINDOWS\system32> #Path where the config file is being saved
$configPath = 'c:\users\config.xml'

#Saving config file
$XMlcontent | Set-Content $configPath

#Loading xml as config
[XML] $configXml = Get-Content -Path $configPath -ErrorAction 'Stop'



Now let's check what we have got in that XML object i.e $configXml



PS C:\WINDOWS\system32> $configXml

xml                            config
---                            ------
version="1.0" standalone="yes" config




We saw how the XML file can be loaded easily with PowerShell and using the configuration data. The implementation is very straightforward and involves casting the loaded content with [XML] into an XML file. This allows us to directly work with IntelliSense and find our configuration properties easily.


We have the object we can now try various tasks like parsing the XML,reading the top nodes, Filtering or searching tags/values. Let's understand with an example.

Let's try to fetch all the PCType values.



PS C:\WINDOWS\system32> $configXml.config.PCType.Type

Name       Value
----       -----
Desktop PC D    
Notebook   N    
Tablet PC  T    


I also learned about the grid view which outputs the results in a screen in tabular format.



PS C:\WINDOWS\system32> $configXml.config.PCType.Type | Out-GridView




Filtering the only type of notebook can be done by applying the where-object. we will see in the below example how we can achieve the same.




PS C:\WINDOWS\system32> $NotebookCode =  ($configXml.Config.PCType.Type | Where-Object {$_.Name -like 'Notebook'}).Value

PS C:\WINDOWS\system32> $NotebookCode
N



Also, we can run some condition along within the object to see if some value exists



PS C:\WINDOWS\system32> if ($configXml.Config.Logdir -ne $null)
{
    $LogDir = $configXml.Config.Logdir
    $LogFile = $configXml.Config.LogFile
}

PS C:\WINDOWS\system32> $LogDir
E:\Logs\

PS C:\WINDOWS\system32> $LogFile
SCCMLogs.txt



It is possible to use filtering and searching to find configuration properties. Especially when you are working with very complex configuration files, this technique might come in handy.

In the next example๐Ÿ™, we will take a more programmatic approach to find the values of an XML file by using XPath filters.

XPath filters allow us to find and retrieve objects in bigger, more complex XML files.



[xml]$xml = Get-Content 'C:\path\to\your.xml'
$xml.selectNodes('//person') | select Name




Just as regular expressions are the standard way to interact with plain text, XPath is the standard way to interact with XML. Because of that, XPath is something you are likely to run across in your travels. Several cmdlets support XPath queries: Select-Xml, Get-WinEvent, and more.

Here we have an example of working with Xpath

PS C:\WINDOWS\system32> $Xpath = "/config/PCType"

PS C:\WINDOWS\system32> Select-Xml -Path $Path -XPath $Xpath | Select-Object -ExcludeProperty Node

Node   Path               Pattern       
----   ----               -------       
PCType C:\temp\config.xml /config/PCType



To make use of XPath filters, you can work with the Select-Xml cmdlet and add the XPath filter as a string. We used a simple filter here to retrieve the objects for a specific structure with "/Types/Type" , and to retrieve all values for all included types recursively with "//config".


Conclusion:
In the past, XML has been widely used as an option for storing application data. XML has some limitations though. It begins to struggle as your XML files increase in size (>1 MB), or if many people try to work with them simultaneously. But it still remains powerful when we are working with configuration or dynamic properties handling.

Happy Coding ๐Ÿ‘