Building a Kivy Application Using Django (2024)

Kivy is a popular library for developing media-rich, multi-touch enabled applications that can run across all major platforms. However, there may be situations that need your application to get access to and manipulate data provided by a web server hosted at a site.

In this article, we are going to learn how to create a Kivy application, and how to make requests to a server using the requests library.

We are going to use Django to develop the server that holds the data that we want to manipulate.

Prerequisites

To follow along, it’s important that:

  • You have Django and djangorestframework frameworks installed.
  • You are familiar with building APIs using the Django REST framework.
  • You have the kivy library installed. If you have not installed it, you can run pip install kivy.
  • Basic knowledge of Python is important. Knowing Object-Oriented Programming would help.

Key takeaways

  • Improve your python skills.
  • Learn how to build applications using the kivy library.
  • Learn how to use Django for your kivy applications.

Getting started

We are going to create a simple to-do application that allows one to view available tasks, offers an option for adding a new task.

We will begin by creating the tasks API with djangorestframework and then create our application using kivy.

We will use the requests library to make requests to our Django server.

Creating the tasks API

In a folder of your choice, create a new project by running:

django-admin startproject TodoAPI

In the TodoAPI project, create a new app named tasks that will handle the creation of tasks.

Run the command below to create the app:

python3 manage.py startapp tasks

Your project structure should look something like this:

.└── TodoAPI ├── manage.py ├── tasks │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ └── views.py └── TodoAPI ├── asgi.py ├── __init__.py ├── settings.py ├── urls.py └── wsgi.py

We need to register our tasks app and rest_framework to use the app.

Edit the settings.py file as follows under INSTALLED APPS:

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

Let’s go ahead and create our tasks model. Edit the models.py file to look as follows:

from django.db import models# Create your models here.class Task(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name

Let’s create a serializer.py file that handles the serialization and de-serialization of task instances.

Serialization is the process of saving an object in a way that can be accessed in a uniform format by different applications.

De-serialization is the reverse of serialization.

You may learn more about serialization and de-serialization in the Django REST framework from this site.

Add the following code to the serializer.py file:

from rest_framework import serializersfrom .models import *class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task field = '__all__'

Creating views

We are going to create some views to render data to a web page.

Views are python functions that handle web requests and return web responses. There are different ways to create the views, we will use function-based views.

Function-based views are views in Django written as python functions.

Edit the views.py file to match the following:

from django.shortcuts import renderfrom rest_framework import statusfrom rest_framework.decorators import api_viewfrom rest_framework.response import Responsefrom .serializers import *from .models import *# Create your views here.@api_view(['GET'])def all_tasks(request): tasks = Task.objects.all() serializer = TaskSerializer(tasks, many=True) return Response(serializer.data, status=status.HTTP_200_OK)@api_view(['POST'])def create_task(request): data = request.data serializer = TaskSerializer(data=data) if serializer.is_valid(): return Response(serializer.data, status=status.HTTP_200_OK)

We begin by defining a function all_tasks that will return a response containing all our tasks. The function gets all the tasks with the line tasks = Task.objects.all().

The data is then serialized on the succeeding line, and the function returns the response. The line @api_view(['GET']) is a decorator that takes GET as the HTTP method that the function should respond to.

The same concept applies to the second function, only that this time it takes a POST HTTP method.

Routing views

We then create a urls.py file for routing our views.

Create the file and add the following code:

from django.urls import pathfrom . import viewsurlpatterns = [ path('', views.all_tasks, name='all_tasks'), path('create', views.create_task, name='create_task')]

The mappings above imply that the requests will first be handled by this file and then routed to a corresponding view function.

For instance, when we visit http://127.0.0.1:8000/create, the create_task function is called and implemented.

We have to create a route for our tasks app.

This way, the routing first occurs on the TodoAPI/urls.py file, and then tasks/urls.py.

Therefore, configure our urls.py file in TodoAPI like this:

from django.contrib import adminfrom django.urls import path, includeurlpatterns = [ path('admin/', admin.site.urls), path('', include('tasks.urls'))]

We can now run:

python3 manage.py makemigrations

and

python3 manage.py migrate

When we run:

python3 manage.py runserver

We should have a page similar to this:

Building a Kivy Application Using Django (1)

When you create a task instance as follows:

Building a Kivy Application Using Django (2)

You should be able to see something like this:

Building a Kivy Application Using Django (3)

Our Django API is working! We can now proceed to create the kivy application.

Creating the Kivy application

Let’s create a main.py file in a folder of choice.

Here, we’ll be using the same directory as our TodoAPI project folder.

We are going to get started with these lines of code in the main.py file. The TodoApp is the main entry point of our application and every execution begins from there.

[YOUR-FOLDER]/main.py

from kivy.app import Appclass TodoApp(App): passif __name__ == '__main__': TodoApp().run()

When you run the file, you should get the following result:

Building a Kivy Application Using Django (4)

We are now going to replace the main.py file with the following lines of code:

from kivy.app import Appfrom kivy.uix.screenmanager import ScreenManagerfrom kivy.uix.boxlayout import BoxLayout#menuclass Menu(BoxLayout): pass#Screen Managementclass ScreenManagement(ScreenManager): pass#app classclass TodoApp(App): passif __name__ == '__main__': TodoApp().run()

We also need to create a kv file where all details of user interface is entailed.

Create a todo.kv file and make sure it’s in the same folder as the main.py file. The file should resemble this one:

BoxLayout: orientation: 'vertical' Menu: size_hint_y: .1 manager: screen_manager ScreenManagement: size_hint_y: .9 id: screen_manager<Menu>: orientation: "vertical" ActionBar: top: 0 ActionView: ActionPrevious: ActionButton: text: 'Home' ActionButton: text: 'Add New'

This is what is happening to our files:

  • We begin by creating a Menu class that inherits from BoxLayout class. This menu will contain the buttons that we will use to explore the application.
  • We then proceed by creating the ScreenManger class that manages the display of what is being displayed in the application.
  • In the todo.kv file, we declare a BoxLayout as the main interface that the application displays.
  • We then give the menu a position of bottom set by size_hint_y: .1.
  • We also declare that it’s managed by ScreenManager. We do this by declaring manager: screen_manager.
  • By setting the id property of the ScreenManager as screen_manager, the position of the menu is now on top.
  • We declare the properties of our Menu class.
  • The class will have an action bar that will contain two buttons, the Home action button, and the Add New action button.

Your application should be similar to the one below:

Building a Kivy Application Using Django (5)

We now need to transition to a different screen when creating a task.

Therefore, we need to declare two screens so that one displays the tasks, and another one to add a new task. Both of these screens will be managed by ScreenManager class.

Edit your main.py file to look like this:

from kivy.app import Appfrom kivy.uix.screenmanager import ScreenManager, Screenfrom kivy.uix.boxlayout import BoxLayout#menuclass Menu(BoxLayout): pass#screensclass HomeScreen(Screen): passclass AddScreen(Screen): pass#Screen Managementclass ScreenManagement(ScreenManager): pass#app classclass TodoApp(App): passif __name__ == '__main__': TodoApp().run()

Also, modify the todo.kv file to be as shown below:

BoxLayout: orientation: 'vertical' Menu: size_hint_y: .1 manager: screen_manager ScreenManagement: size_hint_y: .9 id: screen_manager<Menu>: orientation: "vertical" ActionBar: top: 0 ActionView: ActionPrevious: ActionButton: text: 'Home' on_press: root.manager.current = 'screen_home' ActionButton: text: 'Add New' on_press: root.manager.current = 'screen_add'<ScreenManagement>: id: screen_manager HomeScreen: name: 'screen_home' manager: 'screen_manager' AddScreen: name: 'screen_add' manager: 'screen_manager'<HomeScreen>: Label: text: "Home"<AddScreen>: Label: text: "Add to list..."

In the code above:

  • We declare the HomeScreen class and give it a Label instance with the text Home.
  • We also do the same for the AddScreen with the label text Add to list....
  • We have given both screens as children of ScreenManagement.
  • We also specified the functionality of action buttons by enabling access to the screen. We do this by defining on_press: root.manager.current = 'screen_home' and on_press: root.manager.current = 'screen_add'.

You should now be able to explore the two screens and see the “Home” text in the HomeScreen, and “Add to list…” in the AddScreen

Using the Django API

Let’s create a class that has a function which sends requests to our server for available tasks.

Under the class Menu(BoxLayout): declaration, add the following lines of code:

#recycle view for home screenclass MyRecycleView(RecycleView): def __init__(self, **kwargs): super(MyRecycleView, self).__init__(**kwargs) self.load_data() Clock.schedule_interval(self.load_data, 1) def load_data(self, *args): store = requests.get('http://127.0.0.1:8000/').json() list_data = [] for item in store: list_data.append({'text': item['name']}) self.data = list_data

You need to make these imports at the top of the file:

import requestsfrom kivy.clock import Clockfrom kivy.uix.recycleview import RecycleView

Modify your todo.kv file to look like this:

BoxLayout: orientation: 'vertical' Menu: size_hint_y: .1 manager: screen_manager ScreenManagement: size_hint_y: .9 id: screen_manager<Menu>: orientation: "vertical" ActionBar: top: 0 ActionView: ActionPrevious: ActionButton: text: 'Home' on_press: root.manager.current = 'screen_home' ActionButton: text: 'Add New' on_press: root.manager.current = 'screen_add'<ScreenManagement>: id: screen_manager HomeScreen: name: 'screen_home' manager: 'screen_manager' AddScreen: name: 'screen_add' manager: 'screen_manager'<HomeScreen>: BoxLayout: orientation: "vertical" MyRecycleView:<MyRecycleView>: viewclass: 'Label' RecycleBoxLayout: color: 1,1,1,1 default_size: None, dp(56) default_size_hint: 1, None size_hint_y: None height: self.minimum_height orientation: 'vertical'<AddScreen>: Label: text: "Add to list..."
  • The MyRecycleView class is initialized by having a function load_data that makes requests to the server using the requests library.
  • The data is appended to a list containing dictionaries of the tasks with the key text. The function returns the list as a data variable.
  • The function is called every second by setting a clock interval of 1.

In the todo.kv file, we replace the contents of our HomeScreen with a BoxLayout that contains our MyRecycleView class.

We then declare the properties of our MyRecycleView as having BoxLayout that contains a list of labels, each with text received from our server.

You should now be able to see the code task we created in our web-based interface earlier.

Building a Kivy Application Using Django (6)

Let us now handle the functionality of creating a new task.

We begin by creating a form to submit the creation request to our server.

We then add the form to our AddScreen screen. This will make our application complete.

Let’s modify our main.py file to this:

import requestsfrom kivy.app import Appfrom kivy.clock import Clockfrom kivy.properties import ObjectProperty, StringPropertyfrom kivy.uix.label import Labelfrom kivy.uix.recycleview import RecycleViewfrom kivy.uix.screenmanager import ScreenManager, Screenfrom kivy.uix.boxlayout import BoxLayout#menufrom kivy.uix.widget import Widgetclass Menu(BoxLayout): pass#recycle view for home screenclass MyRecycleView(RecycleView): def __init__(self, **kwargs): super(MyRecycleView, self).__init__(**kwargs) self.load_data() Clock.schedule_interval(self.load_data, 1) def load_data(self, *args): store = requests.get('http://127.0.0.1:8000/').json() list_data = [] for item in store: list_data.append({'text': item['name']}) self.data = list_data#screensclass HomeScreen(Screen): passclass AddNewForm(Widget): text_input = ObjectProperty(None) input = StringProperty('') def submit_input(self): self.input = self.text_input.text post = requests.post('http://127.0.0.1:8000/create', json={'name': self.input}) self.input = ''class AddScreen(Screen): def __init__(self, **kwargs): super(AddScreen, self).__init__(**kwargs) self.box = BoxLayout() self.box.orientation = "vertical" self.box.add_widget(Label(text="Add To List...", color="blue",pos_hint={"top": 1})) self.addNewForm = AddNewForm() self.box.add_widget(self.addNewForm) self.add_widget(self.box)#Screen Managementclass ScreenManagement(ScreenManager): pass#app classclass TodoApp(App): passif __name__ == '__main__': TodoApp().run()

Let us also modify the todo.kv to:

BoxLayout: orientation: 'vertical' Menu: size_hint_y: .1 manager: screen_manager ScreenManagement: size_hint_y: .9 id: screen_manager<Menu>: orientation: "vertical" ActionBar: top: 0 ActionView: ActionPrevious: ActionButton: text: 'Home' on_press: root.manager.current = 'screen_home' ActionButton: text: 'Add New' on_press: root.manager.current = 'screen_add'<ScreenManagement>: id: screen_manager HomeScreen: name: 'screen_home' manager: 'screen_manager' AddScreen: name: 'screen_add' manager: 'screen_manager'<HomeScreen>: BoxLayout: orientation: "vertical" MyRecycleView:<MyRecycleView>: viewclass: 'Label' RecycleBoxLayout: color: 1,1,1,1 default_size: None, dp(56) default_size_hint: 1, None size_hint_y: None height: self.minimum_height orientation: 'vertical'<AddNewForm>: text_input: input TextInput: id: input pos: root.center_x - 220, 300 size: 400,50 Button: size: 130,40 pos: root.center_x - 100, 200 text: 'Submit' on_release: root.submit_input()

The AddNewForm contains a function submit_input that makes a POST request to the server passing the input text as data.

The form has a TextInput that one can type the task, and a button that calls the submit_input function when released.

We then declare a BoxLayout class that will contain the AddNewForm and a label text “Add to list…”

When you now click Add New, you should now see the following:

Building a Kivy Application Using Django (7)

When you create a task, say “Complete application”, and click submit button once then click Home, you should have the following:

Building a Kivy Application Using Django (8)

Conclusion

In this tutorial, we have covered the basics of kivy by creating a simple todo kivy application that allows one to view and add tasks.

We have also seen how we can use Django as a back-end for the application by creating a server that holds our tasks.

With this knowledge, you can create similar applications to suit your different needs.

Further reading

The following are important links that will help you create kivy applications and build APIs using Django and the Django REST framework:

Peer Review Contributions by: Srishilesh P S

Building a Kivy Application Using Django (2024)

FAQs

Is Kivy production ready? ›

I would say yes. Kivy has always been my first choice for mobile app development with Python. Most Python GUI frameworks focus on desktop development. Kivy can do desktop development, but I don't recommend that.

Is Kivy good for making apps? ›

If you're a Python developer thinking about getting started with mobile development, then the Kivy framework is your best bet. With Kivy, you can develop platform-independent applications that compile for iOS, Android, Windows, MacOS, and Linux.

Can Django be used with Kivy? ›

In this tutorial, we have covered the basics of kivy by creating a simple todo kivy application that allows one to view and add tasks. We have also seen how we can use Django as a back-end for the application by creating a server that holds our tasks.

Should I learn Django or Kivy? ›

Both are worth learning. Django is used for making web apps (and web APIs) with python. Kivy is used for making mobile apps with python. Both are typically used for different reasons, you could even use them together (A kivy app with django as a backend).

Is Kivy professional? ›

Kivy is a community project, led by professional software developers, who are responsible for developing and supporting Kivy, alongside of the community. We also work for companies that use Kivy for their professional products.

How difficult is Kivy? ›

Though Kivy is good to create innovative applications with multi-touch functionalities, the user has to code for it, making it comparatively difficult for the user, unlike Flutter, which provides various ready-to-use widgets for creating the attractive UI of the applications.

Is Kivy fast enough? ›

Kivy is fast. This applies to both application development and application execution speeds. We have optimized Kivy in many ways. We implement time-critical functionality on the C level to leverage the power of existing compilers.

Is Kivy easier than tkinter? ›

For simple programs, tkinter is a lot more straightforward and easier to get started with. Plus its library is built into the standard python installation package. Kivy offers more flexibility and is more complicated, but it also has support for mobile (android + IOS).

Is Kivy front end or backend? ›

Kivy is a Python-based library and can be used to develop the Frontend for your app. Kivy can be used as a Frontend library and for the backend, one can use Python.

Which Python version is best for Kivy? ›

Kivy 2.1.0 officially supports Python versions 3.7 - 3.10.

Is Django good for mobile backend? ›

Django applications include both frontend and backend.

Is PyQt better than Kivy? ›

In this article, we conclude that there is no much difference in Kivy or PyQt when speaking about working on GUI in Python, but they both are frameworks that work on different applications such Kivy is much better for mobile apps and other multi-touch apps than desktop apps, whereas PyQt is much better for desktop apps ...

Is Django still relevant 2022? ›

The demand for Django professional is increasing every single day with high demanding salary and career launches. The average salary of a Django developer is $120,000 per year.

Do professionals use Django? ›

Django is a Python-based web framework giving developers the tools they need for rapid, hassle-free development. You can find that several major companies employ Django for their development projects. Here are 9 global companies using Django: Instagram.

What framework is better than Django? ›

Django, as discussed, can sometimes be monolithic. Other full stack frameworks can also be too complex for small, basic websites and applications that do not require a lot of features. Python has a series of well-designed micro frameworks such as Flask, Bottle and CherryPy that work perfectly with small-scale websites.

What are the disadvantages of Kivy? ›

Disadvantages
  • Non-native looking User Interface.
  • Bigger package size (because Python interpreter needs to be included).
  • Lack of community support (Kivy Community isn't particularly large).
  • Lack of good examples and documentation.
Jan 30, 2020

Is it worth learning Kivy? ›

Kivy is a python UI framework, it's done mainly in python, not a wrappper around an UI library done in another language, that makes it really easy to extend from python, and customize exactly how you want it, all the pieces are there for you, not just the ones the interface exposes to you.

Are Kivy apps slow? ›

Many people state that kivy is slow. While this may be true it is mostly due to that python is slow to run on android devices. Thus it is in the programmer's hands to properly optimize their code so as to create a performant application.

Does Kivy have a GUI? ›

Build and distribute beautiful Python cross-platform GUI apps with ease. Kivy runs on Android, iOS, Linux, macOS and Windows. Get started! Kivy has been built to be easy to use, cross-platform and fast.

Can I use OpenCV with Kivy? ›

I've done heavy computation using OpenCV within Kivy. No issues, it just works.

Is Kivy used for game development? ›

In this Kivy course, you will learn to create games and applications with Python for every platform (Windows, Mac, iOS, Android). Jonathan Roux developed this course. Jonathan has created many courses on a variety of platforms. First you will learn how to use the Kivy library.

Should I learn flutter or Kivy? ›

it's easier to build beautiful UI with Flutter than Kivy because Flutter gives you more ready-to-use components by default and more control over the pixels. the community support for Flutter is stronger than Kivy because Flutter is backed by Google and it's probably more famous as of now.

What is the easiest GUI for Python? ›

Python Tkinter

Tkinter is the standard built-in GUI library for Python, and, with over 41,000 stars on GitHub, it's the most popular Python GUI framework. It's a fast and easy-to-use Python GUI library, making it the go-to library for building a Python GUI application.

What is the best GUI in Python? ›

10 Best Python Libraries for GUI
  • PyQt5.
  • Tkinter.
  • Kivy.
  • PySimpleGUI.
  • Libavg.
  • PyForms.
  • PySide2.
  • Wax.
Jul 8, 2022

What is the best GUI module for Python? ›

1–PyQt5. PyQt5 is a very well-known GUI framework used by both Python coders and UI designers. One of its components, the PyQt package, is built around the Qt framework, which is a leading cross-platform GUI design tool for just about any kind of application.

Is tkinter better than Kivy? ›

Installation Process

Hence the installation-wise Tkinter is better when compared to Kivy, which is complex to learn and install for developers sometimes.

Can I use Tensorflow in Kivy? ›

You can use the Jupyter notebook in notebooks to create a Tensorflow Lite model file. A dummy example is provided for testing purposes.

Which Python framework is best for Android app development? ›

Python Mobile App Development Frameworks: The Options
  • The Kivy Framework. Kivy is a Python mobile app development framework that lets you create cross-platform apps. ...
  • The BeeWare Framework. The BeeWare framework is a collection of tools for developing apps in Python. ...
  • The Django Framework.
Jul 14, 2022

Is Kivy still active? ›

New versions of Kivy are being released, New Widgets are being added to the Kivy garden also. This shows Kivy is not dead it is still alive. How many months will it take to learn Python to develop an application with Kivy?

Is Kivy a backend? ›

Kivy uses OpenGL and therefore requires a backend that provides it. The backend used is controlled through the USE_OPENGL_MOCK and USE_SDL2 compile-time variables and through the KIVY_GL_BACKEND runtime environmental variable.

Do I need to learn Python before Kivy? ›

Yes its perfectly fine to learn kivy after learning the basics of python. Kivy can also be a good learning experience as well. It helped me to understand OOP in python a little.

What is the disadvantage of Django? ›

It also has its own set of pros and cons. The benefits of Django are rapid development, fast processing, and scalability whereas; the disadvantages revolve around its monolithic nature and inability to create smaller projects.

Is Django getting outdated? ›

There is a future at least 10 years out. No django dev is becoming obsolete for at least a decade. We are literally just entering the era of python.

Is Python Django outdated? ›

Even though Django never got to the same level of popularity as Ruby, it has managed to grow over the years. I've personally been using it for over 15 years. Version 3.1 was recently released as of a few months ago. Some of the largest websites in the world using Django are Instagram, Pinterest & Mozilla.

Is Kivy better than PyQt? ›

In this article, we conclude that there is no much difference in Kivy or PyQt when speaking about working on GUI in Python, but they both are frameworks that work on different applications such Kivy is much better for mobile apps and other multi-touch apps than desktop apps, whereas PyQt is much better for desktop apps ...

Can Kivy be used for game development? ›

In this Kivy course, you will learn to create games and applications with Python for every platform (Windows, Mac, iOS, Android).

Is tkinter faster than Kivy? ›

Tkinter is the most commonly used Python interface for faster and easier ways of creating GUI applications.

Is Kivy App slow? ›

Many people state that kivy is slow. While this may be true it is mostly due to that python is slow to run on android devices. Thus it is in the programmer's hands to properly optimize their code so as to create a performant application.

Top Articles
Latest Posts
Article information

Author: Mr. See Jast

Last Updated:

Views: 5942

Rating: 4.4 / 5 (75 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Mr. See Jast

Birthday: 1999-07-30

Address: 8409 Megan Mountain, New Mathew, MT 44997-8193

Phone: +5023589614038

Job: Chief Executive

Hobby: Leather crafting, Flag Football, Candle making, Flying, Poi, Gunsmithing, Swimming

Introduction: My name is Mr. See Jast, I am a open, jolly, gorgeous, courageous, inexpensive, friendly, homely person who loves writing and wants to share my knowledge and understanding with you.