Flutter signup/login application with Django backend #1
django tutorial flutter django-rest-framework login

April 16, 2020, 12:42 a.m.

Flutter signup/login application with Django backend #1

  1187

Introduction

This series of posts intends to develop a flutter signup/login app working with API calls to Django backend. The idea is to use the DRF to create APIs which can be called by the flutter application. Most of the tutorials I have seen only talk about doing it with Firebase. Since we already will be using PostgreSQL for the Django, let us use that as our server DB and using SQLite with the Flutter Application to store just the Auth token and Username.

Django Rest Framework

We assume people reading this post already know about it but still just an introduction: - DRF allows for making powerful and flexible Web APIs. - DRF provides a lot of authentication schemes out of the box and even allows us to implement custom schemes. - DRF provides an easy way to serialize and deserialize JSON according to your DB Schema. (Model Serializers)

Flutter

Google Flutter is just awesome when it comes to cross-platform app development. The fact that it doesn't convert your code to machine compatible but instead is capable of directly rendering it on the machine is the best.

BloC design pattern

We will use BloC (Business Logic Component) which was announced by Google in GOOGLE I/O' 18. BloC is simply a state management pattern that works on sinks and streams. The widgets monitor the state changes and send them to the BloC using sinks and other widgets monitor those by subscribing to those streams where they expect the relevant data to arrive. The required sections are rebuilt per the state change. Thus Bloc stands in between data and UI and asynchronously maps events to states which rebuild the UI when required.

Let us Start

We will start by creating a new Django project to provide the required APIs for Login and Signup. Go to your desired folder and activate your virtual environment. (You can refer here for the same)

Step 1

  • Create the project by:
django-admin startproject HOME

Note that the project is named HOME, you can name it anything just be consistent in all the places where we use the names in the commands/code that follows. - cd into the project directory and create an app called api by:

python manage.py startapp api

We will use the auth system that Django provides by default. The User model has almost all the required fields that we may need for the Login and Signup. In case you need extra fields like phone number, address, etc. you can always define a new profile model that will have a one to one relationship with the User model. But for the sake of simplicity here, we are going to go with the User model itself. We have the fields first_name, last_name, username, email, and password which we can use to create a new user.

Step 2

  • Install DRF by
pip install djangorestframework
  • and also add it to your installed apps
INSTALLED_APPS = [
    ...
    'rest_framework',
]
  • There are many auth systems available but I am going to go with Token Auth. We need to add that too in our installed apps:
INSTALLED_APPS = [
    ...
    'rest_framework',
    'rest_framework.authtoken',
]
  • We also need to add the following in our settings for us to be able to use the token auth:
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
    ],
}
  • Migrate your changes by:
python manage.py migrate

Run it from HOME/

Step 3

Now that we are all set up and we have the default User model ready for us, we need to start creating our API - Create a file named serializers.py in HOME/api/ and the following code to it:

from django.contrib.auth.models import User
from rest_framework import serializers
from rest_framework.validators import UniqueTogetherValidator


class UserSerializer(serializers.ModelSerializer):

    def create(self, validated_data):
        user = User.objects.create_user(**validated_data)
        return user

    class Meta:
        model = User
        fields = (
            'username',
            'first_name',
            'last_name',
            'email',
            'password',
        )
        validators = [
            UniqueTogetherValidator(
                queryset=User.objects.all(),
                fields=['username', 'email']
            )
        ]

What we did here is we created a serializer in order to map JSON to our model and vice-versa. The unique together validator will allow us to verify that the combination of username and email is unique for any particular user. - edit your HOME/api/views.py and add the following code to it:

from .serializers import UserSerializer
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.permissions import IsAdminUser
from django.contrib.auth.models import User


class UserRecordView(APIView):
    """
    API View to create or get a list of all the registered
    users. GET request returns the registered users whereas
    a POST request allows to create a new user.
    """
    permission_classes = [IsAdminUser]

    def get(self, format=None):
        users = User.objects.all()
        serializer = UserSerializer(users, many=True)
        return Response(serializer.data)

    def post(self, request):
        serializer = UserSerializer(data=request.data)
        if serializer.is_valid(raise_exception=ValueError):
            serializer.create(validated_data=request.data)
            return Response(
                serializer.data,
                status=status.HTTP_201_CREATED
            )
        return Response(
            {
                "error": True,
                "error_msg": serializer.error_messages,
            },
            status=status.HTTP_400_BAD_REQUEST
        )

What we are doing here is creating a get and a post method, the get method allows us to get a list of all the registered users with our application and the post method allows us to create a new user with the required info as specified in our serializer. Also, I added IsAdminUser as the permission class, the reason is that we do not want anyone to spam our server by sending multiple POST requests and creating unnecessary accounts. - Last but not least we will add routes for access to the application. let us create the file HOME/api/urls.py and add the following code to it:

from django.urls import path
from .views import UserRecordView

app_name = 'api'
urlpatterns = [
    path('user/', UserRecordView.as_view(), name='users'),
]
  • We need to include the route for this and the token system in our main urls i.e. edit the file HOME/urls.py and add the following code to it:
from django.contrib import admin
from django.urls import path, include
from rest_framework.authtoken import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('api.urls', namespace='api')),
    path('api-token-auth/', views.obtain_auth_token, name='api-token-auth'),
]
  • We would need to create an admin user by:
python manage.py createsuperuser

Now enter the details asked and use them below.

Accessing our API

Thus, we have successfully created the required endpoint for the API. We can now test it by the following:

Get authentication token

  • Endpoint: http://localhost:8000/api-token-auth/
  • Parameters required : username, password
  • Sample body: json { "username": "admin", "password": "password" }

Get / Post user

  • Endpoint : http://localhost/api/user/
  • GET
  • parameters: auth token as header
  • sample header: json { "Authorization": "TOKEN <token>" }
  • sample response: json { "username": "<username>", "first_name": "<first_name>", "last_name": "<last_name>", "email": "<email>", "password": "<encrypted string>" }
  • POST
  • parameters:
    • header: auth token as header
    • sample: json { "Authorization" : "TOKEN <token>" }
    • body: username, email, first_name, last_name, password
    • sample: json { "username": "<username>", "first_name": "<first_name>", "last_name": "<last_name>", "email": "<email>", "password": "<encrypted string>" }
  • response (on succesful): json { "username": "<username>", "first_name": "<first_name>", "last_name": "<last_name>", "email": "<email>", "password": "<encrypted string>" } I will continue the project and write posts for each part. The end result will be a flutter app working with this API and SQLite DB.

Next: Flutter signup/login application with Django backend #2

Final Post: Flutter signup/login application with Django backend #3

Share this article:

Comments

  • Pranjal Kanel
    Oct. 8, 2020, 9:06 p.m.

    Very helpful! Thank you

  • Sandy
    Oct. 19, 2020, 4:17 a.m.

    Beautiful article. I really wanted to skip to #3 as that is something new but to read it in a series makes it very smooth reading. Well written Also, like to know your comments about FLUTTER User authentication using Google FireStore - whether that is preferable to Django -DRF - User authentication - especially in terms of speed and any other issues you can think of Thanks

  • Ohuru
    Oct. 30, 2020, 10:19 a.m.

    We will be sending email responses to any queries. Please check your inbox for a reply :)

  • DeeynStei
    Sept. 15, 2022, 10:36 a.m.

    asain gay chat phone lines snap chat solo gay school boy <a href="https://free-gay-sex-chat.com/">senior gay chat lines </a>

  • idosorCop
    Aug. 19, 2022, 5:50 p.m.

    Cs Online Support24 <a href=http://iverstromectol.com/>ivermectin stromectol scabies</a> Zithromax Indications

  • GennieStei
    Sept. 16, 2022, 5:43 p.m.

    gay connect chat <a href=https://chatcongays.com>faree gay chat</a> google zoom gay chat rooms

  • MarrisStei
    Sept. 20, 2022, 11:22 a.m.

    essays to buy <a href=https://au-bestessays.org>essay paper writing services</a> write essay service

  • DorolisaStei
    Sept. 21, 2022, 6:39 a.m.

    buy custom essay <a href=https://bestcampusessays.com>write my essay custom writing</a> help me write essay

  • MartyStei
    Sept. 22, 2022, 4:56 a.m.

    best essay <a href=https://besteasyessays.org>college application essay service</a> can t write my essay

  • MerolaStei
    Sept. 23, 2022, 12:48 a.m.

    help write my essay <a href=https://bestessayreviews.net>essay writers canada</a> help on writing an essay

  • AshlenStei
    Sept. 23, 2022, 8:38 p.m.

    best essay editing service <a href=https://bestessaysden.com>help writing a essay for college</a> need help with essay

  • CharitaStei
    Sept. 25, 2022, 10:18 a.m.

    best custom essay site <a href=https://bestsessays.org>buy an essay cheap</a> medical school essay help

  • NaniceStei
    Sept. 26, 2022, 5:17 a.m.

    essay help websites <a href=https://buyacademicessay.com>need help writing a essay</a> common app essay help

  • ChelsaeStei
    Sept. 27, 2022, 12:55 a.m.

    Who wants to write my essay <a href=https://buy-eessay-online.com>best essay writer company</a> medical school essay service

  • PennyStei
    Sept. 27, 2022, 8:03 p.m.

    essays writing service <a href=https://buytopessays.com>law school essay review service</a> college essay writers

  • TammieStei
    Sept. 28, 2022, 3:59 p.m.

    what should i write my essay on <a href=https://cheapessaywritingservice1.com>where can i buy essays online</a> service essay

  • AntonieStei
    Sept. 29, 2022, 11:56 a.m.

    good essay writing websites <a href=https://customcollegeessays.net>buy cheap essays</a> essay writing services online

  • RhiamonStei
    Sept. 30, 2022, 7:34 a.m.

    college admission essay help <a href=https://customessays-writing.org>custom essay UK</a> community service essay sample

  • CharoStei
    Oct. 1, 2022, 2:29 a.m.

    online essay writing service <a href=https://customessaywwriting.com>academic custom essays</a> best essay writing website

  • DronaStei
    Oct. 1, 2022, 8:57 p.m.

    best essay writing service review <a href=https://customs-essays-writing.org>essay review service</a> college essay service

  • LeilahStei
    Oct. 3, 2022, 1:16 p.m.

    cheap write my essay <a href=https://geniusessaywriters.net>top essay writing service</a> help with essay papers

  • CthrineStei
    Oct. 4, 2022, 11:11 a.m.

    academic essay services <a href=https://howtobuyanessay.com>best essay writing</a> my essay writer

  • GinnieStei
    Oct. 7, 2022, 10:59 a.m.

    romeo and juliet essay help <a href=https://lawessayhelpinlondon.com>online essay writing help</a> custom essay writing toronto

  • GinnieStei
    Oct. 9, 2022, 11:05 p.m.

    buy essay writing <a href=https://lawessayhelpinlondon.com>us essay writers</a> buy essay online cheap

  • VivieneStei
    Oct. 12, 2022, 5:26 a.m.

    business school essay writing service <a href=https://ukessayservice.net>custom writing essay</a> help writing a essay for college

  • EasterStei
    Oct. 13, 2022, 8:23 p.m.

    help in essay writing <a href=https://writemyessaycheap24h.com>sat essay writing help</a> essays writing service

  • GroomyBow
    Oct. 23, 2022, 1:33 p.m.

    Sankaranarayanan R, Esmy PO, Rajkumar R, Muwonge R, Swaminathan R, Shanthakumari S, et al <a href=https://bestcialis20mg.com/>cheapest cialis online</a>

  • AshlenStei
    Nov. 23, 2022, 5:32 p.m.

    what is the best custom essay site <a href=https://bestessaysden.com>business school essay writing service</a> cheapest custom essays

  • ChelsaeStei
    Nov. 27, 2022, 7:42 p.m.

    need help writing a essay <a href=https://buy-eessay-online.com>do my essay cheap</a> medical school essay service

  • MarrisStei
    Nov. 16, 2022, 3:49 p.m.

    who will write my essay <a href=https://au-bestessays.org>essay help college</a> services essay

  • PennyStei
    Nov. 29, 2022, 4:52 a.m.

    writing essay service <a href=https://buytopessays.com>help write an essay</a> buy essay papers

  • DorolisaStei
    Nov. 19, 2022, 5:40 p.m.

    write my college essay <a href=https://bestcampusessays.com>essay help sydney</a> write my essay website

  • MartyStei
    Nov. 21, 2022, 12:40 a.m.

    persuasive essay writer <a href=https://besteasyessays.org>essay about military service</a> essay writer funny

  • MerolaStei
    Nov. 22, 2022, 8:45 a.m.

    original essay writing service <a href=https://bestessayreviews.net>help me write my college essay</a> custome essay

  • CharitaStei
    Nov. 25, 2022, 1:17 a.m.

    custom essay writing reviews <a href=https://bestsessays.org>essay writing website reviews</a> write my essay org

  • NaniceStei
    Nov. 26, 2022, 10:27 a.m.

    best essay writing service website <a href=https://buyacademicessay.com>help writing a argumentative essay</a> college application essay editing services

  • skeriLese
    Dec. 7, 2022, 7:25 a.m.

    <a href=http://bestcialis20mg.com/>buy cialis canada pharmacy</a> ZZ, JP, IA, GD, NS, DA, XY, Jv, SC No competing interests declared

  • InessaStei
    Jan. 24, 2023, 3:02 a.m.

    coursework papers <a href=https://brainycoursework.com>coursework project</a> coursework writing

Leave a comment

Related articles

Flutter signup/login application with Django backend #3

Flutter signup/login application with Django backend #3

What this post is about In the previous two posts, we made an API in Django with the help of …

Read Story
Flutter signup/login application with Django backend #2

Flutter signup/login application with Django backend #2

Next steps This post is in continuation of the other post that written on the same topic. If you have …

Read Story
Converting any HTML template into a Django template

Converting any HTML template into a Django template

Djangify A Python script developed by Ohuru that converts HTML Files / Templates to Django compatible HTML Templates. This post …

Read Story

Stay right up to date

Get great content to your inbox every week. No spam.
Only great content, we don’t share your email with third parties.