How to Build Desktop App Using Tkinter and Django Rest Framework Backend -Part 1

||
Posted 3 years, 10 months ago
||
Views 1956
||
5 min read
1 reaction

In this section, we are going to build the real time Hotel Management System Desktop App using Tkinter and Django Rest Framework. Sounds interesting right smiley.

Before jump into the code, are you interested to see the final outcome, if yes then here it is,

 

Lets seggregate the entire development in 2 steps,

  •      Front End(Desktop App)
  •      BackEnd(Django Rest Framework)

Lets start with Backend design ,

First things first, as we know , we have to create the project in Django,

django-admin startproject hotelmanagement

Then we need to create the app to handle the models and api, and we named as "hotel" as we are dealing with HMS(Hotel Management System) software.

python manage.py startapp hotel

Its time to create model in newly created app,

Below are the models, which we are going to use for this demo purpose,

from django.db import models
from django.contrib.auth.models import User
# Create your models here.


class Room(models.Model):
    room_num = models.IntegerField(blank=True, null=True)
    guest = models.ForeignKey(User, on_delete=models.CASCADE)
    check_in = models.DateField(blank=True, null=True)
    check_out = models.DateField(blank=True, null=True)

    def __str__(self):
        return str(self.room_num)

As we mentioned, we are going to use Django Rest Framework as a backend engine, now its time to install DRF(Shortcut of Django Rest Framework)

So we need to install DRF like below,

pip install djangorestframework

As we have added model & DRF, now we can add this in our settings.py file like below and run our migrations command,

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

    'hotel',

    'rest_framework',
    'rest_framework.authtoken',

]

If you notice the INSTALLED_APPS , we have added rest_framework.authtoken as well. We will come to this later why we have added this,

python manage.py makemigrations

python manage.py migrate

Ok So far so good right smiley

Now, we have to think about exposing our model data to outside of the Django, here we can build the API in many ways, but I would like to have my API's in same app but new folder so structure should be like this,

As you see the above image, created the "api" folder with in the app to handle the API's .

Now, its time to create our serializers.py for all CRUD operartion, final serializers.py file looks like below,

from rest_framework.serializers import(
    HyperlinkedIdentityField,
    ModelSerializer
)

from hotel.models import Room


class RoomCreateUpdateSerializer(ModelSerializer):
    class Meta:
        model = Room
        fields = [
            'id',
            'room_num',
            'guest',
            'check_in',
            'check_out'

        ]


class RoomListSerializer(ModelSerializer):
    class Meta:
        model = Room
        fields = [
            'id',
            'room_num',
            'guest',
            'check_in',
            'check_out'

        ]


class RoomDetailSerializer(ModelSerializer):
    class Meta:
        model = Room
        fields = [
            'id',
            'room_num',
            'guest',
            'check_in',
            'check_out'

        ]

Lets create the views.py file to handle the API requests,

from django.db.models import Q
from rest_framework.generics import (
    ListAPIView,
    RetrieveAPIView,
    DestroyAPIView,
    UpdateAPIView,
    CreateAPIView
)

from hotel.models import Room
from .serializers import (
    RoomListSerializer,
    RoomDetailSerializer,
    RoomCreateUpdateSerializer
)


class RoomCreateAPIView(CreateAPIView):
    queryset = Room.objects.all()
    serializer_class = RoomCreateUpdateSerializer


class RoomDetailAPIView(RetrieveAPIView):
    queryset = Room.objects.all()
    serializer_class = RoomDetailSerializer
    lookup_field = 'pk'


class RoomUpdateAPIView(UpdateAPIView):
    queryset = Room.objects.all()
    serializer_class = RoomDetailSerializer
    lookup_field = 'pk'

    #lookup_url_kwarg = "abc"

    def perform_update(self, serializer):
        serializer.save(user=self.request.user)


class RoomDeleteAPIView(DestroyAPIView):
    queryset = Room.objects.all()
    serializer_class = RoomDetailSerializer
    lookup_field = 'pk'


class RoomListAPIView(ListAPIView):
    queryset = Room.objects.all()
    serializer_class = RoomListSerializer

I think , we have almost crossed 50 % of development. Is it? No, we have to expose the URLS and validate the END_POINTS,

from django.urls import path, include

from .views import (
    RoomListAPIView,
    RoomDetailAPIView,
    RoomUpdateAPIView,
    RoomDeleteAPIView,
    RoomCreateAPIView
)

app_name = 'todo-api'
urlpatterns = [

    path('', RoomListAPIView.as_view(), name='list'),
    path('create/', RoomCreateAPIView.as_view(), name='create'),
    path('<pk>/', RoomDetailAPIView.as_view(), name='detail'),
    path('<pk>/edit/', RoomUpdateAPIView.as_view(), name='update'),
    path('<pk>/delete/', RoomDeleteAPIView.as_view(), name='delete'),

]

Above urls.py has to be under api folder if you follow the same structure as like here,

Now, we can add this url into our project URLS.PY file like below,

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


urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include("hotel.api.urls")),

]

Now, its time to test our API's before jump into front end development, in order to test the API's, DRF has browsable api to check that, we can navigate to localhost:8000/api/

Woow. We can see our data in cool fashion way. 

Now, we can go to update, delete & create API end points to validate it,

Update End Point --> http://localhost:8000/api/1/edit/

Create End Point --> http://localhost:8000/api/create/

Delete End Point --> http://localhost:8000/api/1/delete/

Until we have just created the Models and END_POINTS not an authentication mechanism,

Now, its time to deal with Authentication approach in DRF, as we are going to build the Desktop native apps, we should have an option to login from our front end using some kind of approach. ie where we have to think about Token Authentication.

Lets add the below config in settings.py file,

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
    ]
}

In order to use the token for each user, we have to generate the token automatically and assign to that user. but for now , we are going to create the token manually and use it for accessing the data in front end application,

Add the below api-token url in project urls.py file,this will help us to access the token,

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-auth/', include('rest_framework.urls')),
    path('api/', include("hotel.api.urls")),
    path('api-token-auth/', views.obtain_auth_token, name='api-token-auth'),
]

Lets generate the token for admin user manually using drf_token command just like below,

python manage.py drf_create_token admin

This will create the token something like this,

token admin
Generated token e7487bb528dcf1c2e73414ae2095294f01dfb447 for user admin

Now we can use this token to access the api's for CRUD operations.

Ahhhh !!!. So far we have build the backend stuff in order to accomdate the data rendering in front end. We will see front end design in next section.

Also , we will upload the videos of this project in our course sections, How to Build Desktop app using DRF

Happy Coding !!!


1 reaction

Discussion


Joined on April 19, 2020

Latest Videos