Android Sliding Menu using Navigation Drawer in Flutter[Tutorial+Example]

Introduction:

You might have noticed that a lot of android applications introduced a sliding panel menu to navigate between major modules of the application. In flutter, you can use the drawer widget to attain the navigation drawer with sliding menus. Most of the time Sliding Menu (Navigation Drawer) will be hidden and can be shown by swiping the screen from left edge to right or tapping the app icon on the app bar.

In this post, We are going to design and implement a navigation drawer using a drawer widget in a flutter to learn more about it you can view the below .




Demo:

The final result of the app

Prerequisites

This tutorial assumes a little knowledge of Flutter and its widget usages.

Visual Studio Code editor / Android studio installed on your machine if you haven’t yet. We’ll use it in our tutorial.


Project Setup:

Create a new flutter project with the name flutter_navigation_drawer. We are going to take an example from Gmail App for the navigation drawer.


Using Material Design, there are two primary options for navigation: tabs and drawers. When there is insufficient space to support tabs, drawers provide a handy alternative.

In Flutter, use the Drawer widget in combination with a Scaffold to create a layout with a Material Design drawer. This recipe uses the following steps:


  • Create a Scaffold.
  • Add a drawer.
  • Populate the drawer with items + close it.


1. Create a Scaffold

To add a drawer you need to wrap it in a Scaffold widget. you can view it in below example:


Scaffold(
  drawer: // Add a Drawer here in the next step.
);
2. Add a drawer 
 Next we are going to add the drawer widget to the scaffold. you can view it in below example:

Scaffold(
  drawer: Drawer(
    child: // Populate the Drawer in the next step.
  )
);
3. Update your main.dart 

We are going to design a new widget for the drawer part. Create a file named maindrawer.dart inside lib directory and we going to look the example little later but before that we will try to update our main.dart file add the below code.

import 'package:flutter/material.dart';

import 'maindrawer.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        iconTheme: IconThemeData(
            color: Colors.black
        ),
        title: Text("Gmail",style: TextStyle(color: Colors.red,fontSize: 22.0),),
        backgroundColor: Colors.white,
      ),
      //Now we are going to open a new file
      // where we will create the layout of the Drawer
      drawer: Drawer(
        child: MainDrawer(),
      ),
    );
  }
}
3. Populate drawer with items 

Before we populate with a list view we are going to add a container that will hold the text and the list view todo this we are going to add 

crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
"Gmail",
style:TextStyle(
fontSize: 25.0,
fontWeight: FontWeight.w500,
color: Colors.red[300],
),
//textAlign: TextAlign.left,
),

],
Add the list view by using the ListTile widget that will include the options like inbox.mail,snoozed etc and we are going to use the icon to add the icon and text to the list view as below

ListTile(
onTap: (){},//add code to set state on click of the items
leading: Icon(
Icons.inbox, // add the icons to the ListTile
color: Colors.black,
),
trailing: Text( // trailling is addded to last part of the listview
"99+"
),
title:Text(
"Inbox"
),
The Complete Code to populate the drawer with data . Add this code to the maindrawer.dart

import 'package:flutter/material.dart';

class MainDrawer extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Container(
          child: Padding(
            padding: EdgeInsets.only(top:50.0,left: 20.0),

            child: Column(
              //mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                Text(
                  "Gmail",
                    style:TextStyle(
                        fontSize: 25.0,
                        fontWeight: FontWeight.w500,
                        color: Colors.red[300],
                    ),
                  //textAlign: TextAlign.left,
                ),

              ],
            ),

          ),

        ),
        SizedBox(
          height: 20.0,
        ),
        ListTile(
          onTap: (){},
          leading: Icon(
            Icons.inbox,
            color: Colors.black,
          ),
          trailing: Text(
            "99+"
          ),
          title:Text(
            "Inbox"
          ),

        ),
        ListTile(
          onTap: (){},
          leading: Icon(
            Icons.star_border,
            color: Colors.black,
          ),
          title:Text(
              "Starred"
          ),

        ),
        ListTile(
          onTap: (){},
          leading: Icon(
            Icons.snooze,
            color: Colors.black,
          ),
          title:Text(
              "Snoozed"
          ),

        ),ListTile(
          onTap: (){},
          leading: Icon(
            Icons.label_important,
            color: Colors.black,
          ),
          title:Text(
              "Important"
          ),

        ),ListTile(
          onTap: (){},
          leading: Icon(
            Icons.inbox,
            color: Colors.black,
          ),
          title:Text(
              "draft"
          ),

        ),ListTile(
          onTap: (){},
          leading: Icon(
            Icons.inbox,
            color: Colors.black,
          ),
          title:Text(
              "sent"
          ),

        )
      ],
    );
  }
}
Conclusion:

 We learned how to use the drawer widget within flutter and implement it within your app. we can improve this code by creating a function for the list and just using the reference to add the list items based on title and icons and parameters. We will code those in the next part when we implement the ontap() method till then Happy Coding :-)


Learn to design a beautiful Login/Signup (registration flow) in Flutter

 Introduction:

In this post, we are going to learn how to build a beautiful login/signup (registration flow)for your app. We are going to build it from scratch and understand various widgets that you can use to build an elegant screen. You might have already seen some beautiful screens been designed using flutter. Flutter gives you the flexibility to design your own custom widgets and import them to build sleek designs.

Demo

The final result of the app



Prerequisites

This tutorial assumes a little knowledge of Flutter or Dart. JavaScript knowledge will be helpful as well, especially ES6 features. You should have:

Visual Studio Code editor / Android studio installed on your machine if you haven’t yet. We’ll use it in our tutorial.


Project setup

Simply create a new project in flutter and give it the name flutter_login_app.


Directory structure

Once the project is created, open it into Android Studio. We’re using Android studio because it has the most complete Flutter support (Dart syntax, code completion, debugging tools). By default, you should see the following directory structure:

  1. android - where Android-related files are stored. If you’ve done any sort of cross-platform mobile app development before, this, along with the ios folder should be pretty familiar.
  2. ios - where iOS-related files are stored.
  3. lib - This is where you’ll be working most of the time. By default, it contains a main. dart file, this is the entry point file of the Flutter app. we are going to create our own widget for login/signup here.
  4. test - this is where you put the unit testing code for the app. We won’t really be working on it in this tutorial.
  5. pubspec.yaml - this file defines the version and build number of your app. It’s also where you define your dependencies. If you’re coming from a web development background, this file has the same job description as the package.json file so you can define the external packages (from the Dart packages website) you want to use in here.

Note that I’ve skipped on other folders and files because most of the time you won’t really need to touch them.


First, we will start by creating a new widget file which we will use in the later stages.

Create two dart named login.dart and signup.dart files under the lib folder as seen in the below pics.


Build the UI.

Let start by looking into the main.dart file

Create a new stateless widget class called HomePage.

  • Stateful widget: manages its own internal state and keeps track of it.
  • Stateless widget: while this kind of widget doesn’t. For example, a button doesn’t need to track anything.

We want to have a title with some text, then we have an image or illustration below that we have two buttons more specific Material button widget for login and signup.

To have the flexibility we are going to use the SafeArea widget along with Media queries. Add the below code to get the initial text Hello There!




body: SafeArea(
        child: Container(
          width: double.infinity,
          height: MediaQuery.of(context).size.height,
          padding: EdgeInsets.symmetric(horizontal: 30,vertical: 30),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Text(
                    "Hello There!",
                    style: TextStyle(fontWeight: FontWeight.bold, fontSize: 40),
                  ),
                  SizedBox(height: 30,),
                  Text("Automatic identity verification which enable you to verify your identity",
                      textAlign: TextAlign.center,
                      style: TextStyle(
                        color: Colors.grey[700],
                        fontSize: 15
                      ),
                  ),
                ],
              ),
Next, we are going to add an illustration to our home page ,First, we need to add the assets to pubspec.yaml file Make sure to follow the YAML structure.

assets:
    - assets/Illustration.png 
    
 
We are going to add the illustration inside a container with a height of 1/3 of the screen size inside a media query.

Container(
                height: MediaQuery.of(context).size.height/3,
                decoration: BoxDecoration(
                  image:DecorationImage(image: AssetImage('assets/Illustration.png'))
                ),
              ),
              
  
Next to add two buttons for login/signup. We are going to use the MaterialButton widget with an onpressed() event which we will cover later on how to have the click functionality for a button. To add a material button you can use the below code for the login and signup button: 

Login Button

MaterialButton(
                    minWidth: double.infinity,
                    height:60,
                    onPressed: (){
                      
                    },
                    color: Colors.indigoAccent[400],
                    shape: RoundedRectangleBorder(
                      side: BorderSide(
                        color: Colors.black,
                      ),
                      borderRadius: BorderRadius.circular(40)
                    ),
                    child: Text("Login",style: TextStyle(
                      fontWeight: FontWeight.w600,fontSize: 16,color: Colors.white70

                    ),),

 
Sign up Button

MaterialButton(
                      minWidth: double.infinity,
                      height:60,
                      onPressed: (){
                        
                      },
                      color: Colors.redAccent,
                      shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(40)
                      ),
                      child: Text("Sign UP",style: TextStyle(
                        fontWeight: FontWeight.w600,fontSize: 16,

                      ),),
                    ),	
   


Designing the Login/Sign Up page We are going to design our login and signup page to do that we need to edit our already created login.dart and signup.dart file

Add the below code for login.dart file



import 'package:flutter/material.dart';

class LoginPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
        backgroundColor: Colors.white,
        appBar: AppBar(
          elevation: 0,
          brightness: Brightness.light,
          backgroundColor: Colors.white,
          leading:
          IconButton( onPressed: (){
            Navigator.pop(context);
          },icon:Icon(Icons.arrow_back_ios,size: 20,color: Colors.black,)),
        ),
      body: Container(
        height: MediaQuery.of(context).size.height,
        width: double.infinity,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            Column(
              children: [
                Column(
                  children: [
                    Text ("Login", style: TextStyle(
                      fontSize: 30,
                      fontWeight: FontWeight.bold,
                    ),),
                    SizedBox(height: 20,),
                    Text("Welcome back ! Login with your credentials",style: TextStyle(
                      fontSize: 15,
                      color: Colors.grey[700],
                    ),),
                    SizedBox(height: 30,)
                  ],
                ),
                Padding(
                  padding: EdgeInsets.symmetric(
                    horizontal: 40
                  ),
                  child: Column(
                    children: [
                      makeInput(label: "Email"),
                      makeInput(label: "Password",obsureText: true),
                    ],
                  ),
                ),
                Padding(
                  padding: EdgeInsets.symmetric(horizontal: 40),
                  child: Container(
                    padding: EdgeInsets.only(top: 3,left: 3),
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(40),
                        border: Border(
                            bottom: BorderSide(color: Colors.black),
                            top: BorderSide(color: Colors.black),
                            right: BorderSide(color: Colors.black),
                            left: BorderSide(color: Colors.black)
                        )
                    ),
                    child: MaterialButton(
                      minWidth: double.infinity,
                      height:60,
                      onPressed: (){},
                      color: Colors.indigoAccent[400],
                      shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(40)
                      ),
                      child: Text("Login",style: TextStyle(
                        fontWeight: FontWeight.w600,fontSize: 16,color: Colors.white70
                      ),),
                    ),
                  ),
                ),
                SizedBox(height: 20,),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text("Dont have an account?"),
                    Text("Sign Up",style: TextStyle(
                      fontWeight: FontWeight.w600,
                      fontSize: 18
                    ),),
                  ],
                )
              ],

            ),
          ],
        ),
      ),
    );
  }
}

Widget makeInput({label,obsureText = false}){
  return Column(
    crossAxisAlignment: CrossAxisAlignment.start,
    children: [
      Text(label,style:TextStyle(
        fontSize: 15,
        fontWeight: FontWeight.w400,
        color: Colors.black87
      ),),
      SizedBox(height: 5,),
      TextField(
        obscureText: obsureText,
        decoration: InputDecoration(
          contentPadding: EdgeInsets.symmetric(vertical: 0,horizontal: 10),
          enabledBorder: OutlineInputBorder(
            borderSide: BorderSide(
              color: Colors.grey[400],
            ),
          ),
          border: OutlineInputBorder(
            borderSide: BorderSide(color: Colors.grey[400])
          ),
        ),
      ),
      SizedBox(height: 30,)

    ],
  );
}


Add the below code to signup.dart file

import 'package:flutter/material.dart';

class SignupPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      resizeToAvoidBottomPadding: false,
      backgroundColor: Colors.white,
      appBar: AppBar(
        elevation: 0,
        brightness: Brightness.light,
        backgroundColor: Colors.white,
        leading:
        IconButton( onPressed: (){
          Navigator.pop(context);
        },icon:Icon(Icons.arrow_back_ios,size: 20,color: Colors.black,)),
      ),
      body: SafeArea(
        child: SingleChildScrollView(
          child: Container(
            height: MediaQuery.of(context).size.height,
            width: double.infinity,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Column(
                  children: [
                    Column(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        Text ("Sign up", style: TextStyle(
                          fontSize: 30,
                          fontWeight: FontWeight.bold,
                        ),),
                        SizedBox(height: 20,),
                        Text("Create an Account,Its free",style: TextStyle(
                          fontSize: 15,
                          color: Colors.grey[700],
                        ),),
                        SizedBox(height: 30,)
                      ],
                    ),
                    Padding(
                      padding: EdgeInsets.symmetric(
                          horizontal: 40
                      ),
                      child: Column(
                        children: [
                          makeInput(label: "Email"),
                          makeInput(label: "Password",obsureText: true),
                          makeInput(label: "Confirm Pasword",obsureText: true)
                        ],
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.symmetric(horizontal: 40),
                      child: Container(
                        padding: EdgeInsets.only(top: 3,left: 3),
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(40),
                            border: Border(
                                bottom: BorderSide(color: Colors.black),
                                top: BorderSide(color: Colors.black),
                                right: BorderSide(color: Colors.black),
                                left: BorderSide(color: Colors.black)
                            )
                        ),
                        child: MaterialButton(
                          minWidth: double.infinity,
                          height:60,
                          onPressed: (){},
                          color: Colors.redAccent,
                          shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(40)
                          ),
                          child: Text("Sign Up",style: TextStyle(
                            fontWeight: FontWeight.w600,fontSize: 16,

                          ),),
                        ),
                      ),
                    ),
                    SizedBox(height: 20,),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text("Already have an account? "),
                        Text("Login",style: TextStyle(
                            fontWeight: FontWeight.w600,
                            fontSize: 18
                        ),),
                      ],
                    )
                  ],

                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

Widget makeInput({label,obsureText = false}){
  return Column(
    crossAxisAlignment: CrossAxisAlignment.start,
    children: [
      Text(label,style:TextStyle(
          fontSize: 15,
          fontWeight: FontWeight.w400,
          color: Colors.black87
      ),),
      SizedBox(height: 5,),
      TextField(
        obscureText: obsureText,
        decoration: InputDecoration(
          contentPadding: EdgeInsets.symmetric(vertical: 0,horizontal: 10),
          enabledBorder: OutlineInputBorder(
            borderSide: BorderSide(
              color: Colors.grey[400],
            ),
          ),
          border: OutlineInputBorder(
              borderSide: BorderSide(color: Colors.grey[400])
          ),
        ),
      ),
      SizedBox(height: 30,)

    ],
  );
}

Conclusion:
This is a very simple Flutter Application, demonstrating the Login or Sign-in screen.  Most of the widgets used like Text and FlatButton are surrounded in Container widgets. You may change the colors, padding, margin or backgrounds, to suit the theme of your application. In the next tutorial we are going to develop api using node.js to test the application.

Cheers!
Happy Coding 😀

How to create a Simple TabBar with Tabbarview in Flutter

In this post, we are going to see how to build a simple TabBar in Flutter. We will start with a very basic view to add a tab bar first within an AppBar. We will also see how to add icons and other customizations to a TabBar in a flutter.

Lets get started!

Step 1: Create a project in a flutter in android studio

First Go to your android studio/VS code and create a new flutter app and give the name as flutter_tabs with other default settings.

Step 2: Working with Main.dart

Since you already know that Flutter workes mostly by adding widget and when you run the main dart file the execution of your app starts.

Just give a try to run the app to make sure everything works fine.

To create a TabBar we need to create three things

  • Create a TabController.
  • Create the tabs.
  • Create content for each tab.


Step 3: Add a Stateless Widget to the Main.dart File and give the class name as TabBarDemo

 class TabBardemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}
Step 3.1 Update the Main() Method to execute the widget

void main() {
  runApp(TabBarDemo());
}
Step 4: Adding a TabController 

 Now we can go-ahead and add a TabController. To Make sure the view and the tabs are in sync we are going to use this TabController .You can create a TabController manually or automatically by using the DefaultTabController To add a default Tab Controller you can add the below code in you MaterialApp Widget.

home: DefaultTabController(
        length: 3,
        child: Scaffold())
Step 4.1: Create a Tab

 When a tab is selected, it needs to display content. You can create tabs using the TabBar widget. In this example, create a TabBar with three Tab widgets and place it within an AppBar.

home: DefaultTabController(
        length: 3,
        child: Scaffold(
          backgroundColor: Colors.blueGrey[50],
          appBar: AppBar(
            title: new Text("Simple Tab Demo"),
            backgroundColor: Colors.lightBlue[900],
            bottom: TabBar(
              tabs: [
                Tab(
                   text: ("One"),
                ),
                Tab(
                  text: ("Two"),
                ),
                Tab(
					text: ("Three"),
				)
              ],
            ),
          ),
        ),
      ),

Step 4.2: Add a TabView 

 we need to add content to each tab .To add content to we are going to add TabBarView Widget within body

body: TabBarView(children: [
            Center( child: Text("One",style: TextStyle(fontSize: 50),)),
            Center( child: Text("Two",style: TextStyle(fontSize: 50),)),
            Center( child: Text("Three",style: TextStyle(fontSize: 50),))
          ]),


Step 5:
Run the App (main.dart File) 

 Final Code

import 'package:flutter/material.dart';

void main() {
  runApp(TabBarDemo());
}

class TabBarDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: DefaultTabController(
        length: 3,
        child: Scaffold(
          backgroundColor: Colors.blueGrey[50],
          appBar: AppBar(
            title: new Text("Simple Tab Demo"),
            backgroundColor: Colors.lightBlue[900],
            bottom: TabBar(
              tabs: [
                Tab(
                   text: ("One"),
                ),
                Tab(
                  text: ("Two"),
                ),
                Tab(text: ("Three"),)
              ],
            ),
          ),
          body: TabBarView(children: [
          Center( child: Text("One",style: TextStyle(fontSize: 50),)),
          Center( child: Text("Two",style: TextStyle(fontSize: 50),)),
          Center( child: Text("Three",style: TextStyle(fontSize: 50),))
        ]),
        ),
      ),
    );
  }
}

class TabBardemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

Build REST API in Django Using Rest Framework [Function based views]

1 . Introduction

In this post, we are going to learn about function based views in Django. Django has two types of views; function-based views (FBVs), and class-based views (CBVs). Django originally started out with only FBVs, but then added CBVs as a way to templatize functionality so that you didn’t have to write boilerplate (i.e. the same code) code over and over again.



2. Setup

Let's create a project first and setup URLs (skip this section if you are already aware of this setup).

#Create a fresh virtual environment
mkvirtualenv env (On creating, env will be activated automatically. Activate it if you navigate to a new tab.)

#Install Django 
pip install Django

#Go to your favourite directory and create a new project
django-admin.py startproject StudentService

#Important step. Perform all the operations in this directory. When I say 'project_template' directory in future, it points to the directory present inside this, i.e,. project_directory/project_directory.
cd StudentService
Lets create a sample app 'students'.

python manage.py startapp students

3. Setting Up Project Settings.py
Add 'students' + rest_framework to installed apps in your settings.py files



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

Modify your Database settings as well. We are going to work with MYSQL Database

Add this to your settings.py file


DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'studentdb',
        'USER': 'root',
        'PASSWORD': ''
    }
}

4. Working with models

Let's build the model for our API. In this example, we are going to see how to store students scores for examinations.

We are going to capture ID, NAME & score details of each individual student. 

Add the below code to the models.py inside the student's folder.


from django.db import models

# Create your models here.

class Students(models.Model):
    id = models.IntegerField(primary_key=True)
    name = models.CharField(max_length = 20)
    score = models.DecimalField(max_digits=10,decimal_places=3)

    def __str__(self):
        return self.id+self.name+self.score

5. Adding Serializers

Now its time to create a Serializers for API. 

Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into JSON, XML or other content types. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.

First, create a file called serializers.py and add the below code.


from rest_framework import serializers
from students.models import Students

class StudentSerializers(serializers.ModelSerializer):
    class Meta:
        model = Students
        fields = ["id","name","score"]

in the fields, sections above you can use __all__ to add all the columns for serializations. If you want to capture individual ones you can pass a list of column names.


6. Updating the views.py

Finally, let's create Views.py

First we need to be able to fetch all the results by performing a GET and also should be able to add a new student record.

The below code helps you fetch all records on GET and add new student details. The core of this functionality is the api_view decorator, which takes a list of HTTP methods that your view should respond to. For example, this is how you would write a very simple view that just manually returns some data: 



@api_view(['GET','POST'])
def students_list(request):
    if request.method == 'GET':
        students = Students.objects.all()
        serializers = StudentSerializers(students,many=True)
        return Response(serializers.data)

    elif(request.method == 'POST'):
        serializers = StudentSerializers(data=request.data)
        if serializers.is_valid():
            serializers.save()
            return Response(serializers.data,status=status.HTTP_201_CREATED)
        return Response(serializers.errors,status=status.HTTP_400_BAD_REQUEST)
In the next scenario we are going to see how to work with individual student records using GET,PUT,DELETE

The PK here is the primary key column in your database which is ID in our case. 


api_view(['GET','PUT','DELETE'])
def students_details(request,pk):
    try:
        student = Students.objects.get(pk=pk)
    except Students.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializers = StudentSerializers(Students)
        return Response(serializers.data)

    elif request.method == 'PUT':
        serializers = StudentSerializers(Students,request.data)
        if serializers.is_valid():
            serializers.save()
            return Response(serializers.data)
        return Response(serializers.errors,status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        Students.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)
Make sure to import all the necessary modules 


from students.models import Students
from students.serializers import StudentSerializers
from rest_framework.response import Response
from rest_framework import status
from rest_framework.decorators import api_view

7. Finally Urls.py
Last we will add the URLs to make sure we are able to hit it via the endpoints

Add/update the URL patterns in urls.py in StudentService


urlpatterns = [
    path('admin/', admin.site.urls),
    path('students/', views.students_list),
    path('students/', views.students_details),

]


This function based views is very easy to implement and it’s very useful but the main disadvantage is that on a large Django project, usually a lot of similar functions in the views. If all objects of a Django project usually have CRUD operations so this code is repeated again and again unnecessarily and this was one of the reasons that the class-based views and generic views were created for solving that problem.

Conclusion:

We saw how to use the function based views in this post while there are other types of views as well which we will cover in upcoming posts. if you want to know if function based views are best among all then it all depends on the context and the needs. As I mentioned in the beginning of this post, class-based views does not replace function-based views. There are cases where function-based views are better. In other cases, class-based views are better.


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!!