Create a Todo app with the Django REST framework

Create a simple TODO app using the Django REST framework.

** Features of the app to create **

--Single page app that manages the creation / completion of TODO --Store TODO in SQLite3 --Use Django REST framework --Create RESTful API

** Environment / Version ** Windows 7 Python 3.4.3 Django 1.8.2 Django REST framework 3.1.2

** Deliverables ** https://github.com/koji-ohki-1974/django-rest-todo

Preparation

It's assumed that Python and Django are already installed.

Introducing the Django REST framework

Run the following command to install the Django REST framework.

pip install djangorestframework

Creating a project

Create a Django project. Execute the following command in any folder.

django-admin.py startproject django_rest_todo

Database setup

Initialize the database and create a superuser.

cd django_rest_todo
python manage.py migrate
python manage.py createsuperuser

Set the superuser ID, email address, and password.

item value
Username admin
Email address [email protected]
Password admin

Server startup / operation check

Execute the following command.

python manage.py runserver

Start your browser and access [http: // localhost: 8000 /](http: // localhost: 8000 /). If the project has been created successfully, the screen "It worked!" Will be displayed.

Quit the server with "CTRL + C".

Creating an application

In the project folder, execute the following command to create an application.

cd django_rest_todo
django-admin.py startapp api

Change the project settings. Change "settings.py" as follows.

settings.py (excerpt)


INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'django_rest_todo.api',
)

MIDDLEWARE_CLASSES = (
#  'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
#  'django.middleware.csrf.CsrfViewMiddleware',
#  'django.contrib.auth.middleware.AuthenticationMiddleware',
#  'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
#  'django.contrib.messages.middleware.MessageMiddleware',
#  'django.middleware.clickjacking.XFrameOptionsMiddleware',
#  'django.middleware.security.SecurityMiddleware',
)

Creating an API

Todo model

Define the Todo model. Edit "api / models.py" and add the Todo class.

api/models.py


from django.db import models

class Todo(models.Model):
    text = models.TextField()

When the model definition is completed, it will be reflected in the database. Execute the following command.

cd ..
python manage.py makemigrations api
python manage.py sqlmigrate api 0001
python manage.py migrate

Creating a serializer

Defines a serializer that maps the model to JSON. Create "api / serializers.py".

api/serializers.py


from .models import Todo
from rest_framework import serializers

class TodoSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Todo
        fields = ('id', 'text')

Create view

Create a view for REST. Add the TodoViewSet class to "api / views.py".

api/views.py


from rest_framework.viewsets import ModelViewSet
from .models import Todo
from .serializers import TodoSerializer

class TodoViewSet(ModelViewSet):
    queryset = Todo.objects.all()
    serializer_class = TodoSerializer

API routing

Set the routing so that the API can be processed. Modify "urls.py".

urls.py


from django.conf.urls import include, url
from rest_framework.routers import DefaultRouter
from .api import views

router = DefaultRouter()
router.register(r'todos', views.TodoViewSet)

urlpatterns = [
    url(r'^api/', include(router.urls)),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]

Server startup / operation check

Start the server again and check the operation of the API. Execute the following command.

python manage.py runserver

Launch your browser and access:

http://localhost:8000/api/ http://localhost:8000/api/todos/

Quit the server with "CTRL + C".

Creating a front end

Static file

Specifies the location of static files (.html and .js). Edit "settings.py" and add the following:

settings.py


STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
)

Create a "static" folder.

mkdir static

HTML file

Create a todo list screen. Create "static / index.html".

static/index.html


<!doctype html>
<html ng-app="djangoTodo">
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">

	<title>Django REST framework Todo App</title>

	<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
	<style>
		html                    { overflow-y:scroll; }
		body                    { padding-top:50px; }
		#todo-list              { margin-bottom:30px; }
	</style>

	<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
	<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
	<script src="core.js"></script>

</head>
<body ng-controller="mainController">
	<div class="container">

		<div class="jumbotron text-center">
			<h1>Todo list<span class="label label-info">{{ todos.length }}</span></h1>
		</div>

		<div id="todo-list" class="row">
			<div class="col-sm-4 col-sm-offset-4">

				<div class="checkbox" ng-repeat="todo in todos">
					<label>
						<input type="checkbox" ng-click="deleteTodo(todo.id)"> {{ todo.text }}
					</label>
				</div>

			</div>
		</div>

		<div id="todo-form" class="row">
			<div class="col-sm-8 col-sm-offset-2 text-center">
				<form>
					<div class="form-group">

						<input type="text" class="form-control input-lg text-center" placeholder="Please enter Todo" ng-model="formData.text">
					</div>

					<button type="submit" class="btn btn-primary btn-lg" ng-click="createTodo()">add to</button>
				</form>
			</div>
		</div>

	</div>

</body>
</html>

JavaScript file

In JavaScript, describe the process to call the API. Create "static / core.js".

static/core.js


var djangoTodo = angular.module('djangoTodo', []);

function mainController($scope, $http) {

    $scope.readTodos = function() {
        $http.get('/api/todos/')
            .success(function(data) {
                $scope.formData = {};
                $scope.todos = data;
                console.log(data);
            })
            .error(function(data) {
                console.log('Error: ' + data);
            });
    };

    $scope.createTodo = function() {
        $http.post('/api/todos/', $scope.formData)
            .success(function(data) {
                console.log(data);
                $scope.readTodos();
            })
            .error(function(data) {
                console.log('Error: ' + data);
            });
    };

    $scope.deleteTodo = function(id) {
        $http.delete('/api/todos/' + id + '/')
            .success(function(data) {
                console.log(data);
                $scope.readTodos();
            })
            .error(function(data) {
                console.log('Error: ' + data);
            });
    };

    $scope.readTodos();

}

redirect

Set to redirect the request to the top page "/" to "static / index.html". Modify "urls.py".

urls.py


from django.conf.urls import include, url
from django.views.generic import RedirectView
from rest_framework.routers import DefaultRouter
from .api import views

router = DefaultRouter()
router.register(r'todos', views.TodoViewSet)

urlpatterns = [
    url(r'^api/', include(router.urls)),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
    url('', RedirectView.as_view(url='/static/index.html')),
]

Operation check

Server startup / operation check

Start the server.

python manage.py runserver

Start your browser and access [http: // localhost: 8000 /](http: // localhost: 8000 /). When the todo list is displayed, you are done.

Recommended Posts

Create a Todo app with the Django REST framework
Create a Todo app with Django REST Framework + Angular
Create a REST API to operate dynamodb with the Django REST Framework
Create a Todo app with Django ③ Create a task list page
Create a Todo app with Django ⑤ Create a task editing function
Create a Todo app with Django ① Build an environment with Docker
Create RESTful APIs with Django Rest Framework
Create a homepage with django
Create a Todo app with Django ④ Implement folder and task creation functions
Django REST framework with Vue.js
Login with django rest framework
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 1 ~
Create APIs around user authentication with Django REST Framework
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 2 ~
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 3 ~
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 4 ~
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 5 ~
[Django] Use MessagePack with Django REST framework
Create a file uploader with Django
I want to create an API that returns a model with a recursive relationship in the Django REST Framework
Understand the benefits of the Django Rest Framework
Miscellaneous notes about the Django REST framework
Web App Development Practice: Create a Shift Creation Page with Django! (Shift creation page)
Create a GUI app with Python's Tkinter
CRUD POST with Nuxt & Django REST Framework
CRUD GET with Nuxt & Django REST Framework ①
Create a simple web app with flask
Create your first app with Django startproject
Web App Development Practice: Create a Shift Creation Page with Django! (Introduction)
CRUD PUT, DELETE with Nuxt & Django REST Framework
Create a dashboard for Network devices with Django!
Django REST framework A little useful to know.
How to create a multi-platform app with kivy
Create a one-file hello world application with django
A simple to-do list created with Python + Django
How to create a Rest Api in Django
Until you create a new app in Django
Create a translation tool with the Translate Toolkit
Implementing authentication in Django REST Framework with djoser
Create a Django schedule
Django REST framework basics
Django Rest Framework Tips
Create Django Todo list
Create a simple reception system with the Python serverless framework Chalice and Twilio
Try to create a Todo management site using WebSocket with Django (Swamp Dragon)
I tried to create a table only with Django
Create a native GUI app with Py2app and Tkinter
How to create a submenu with the [Blender] plugin
When you want to filter with Django REST framework
Create a tweet heatmap with the Google Maps API
[Django Rest Framework] Customize the filter function using Django-Filter
Transit to the update screen with the Django a tag
Deploy a Django app made with PTVS on Azure
To myself as a Django beginner (1) --Create a project app--
To myself as a Django beginner (4) --Create a memo app--
Create a django environment with docker-compose (MariaDB + Nginx + uWSGI)
Implement hierarchical URLs with drf-nested-routers in Django REST framework
Web App Development Practice: Create a Shift Creation Page with Django! (Write a base template)
Web App Development Practice: Create a Shift Creation Page with Django! (Authentication system processing)
Web App Development Practice: Create a Shift Creation Page with Django! (Experiment on admin page)
[Go language] Create a TUI app with Elm Architecture Create a slightly rich ToDo app with bubble tea