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
It's assumed that Python and Django are already installed.
Run the following command to install the Django REST framework.
pip install djangorestframework
Create a Django project. Execute the following command in any folder.
django-admin.py startproject django_rest_todo
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 |
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".
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',
)
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
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 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
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'))
]
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".
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
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>
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();
}
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')),
]
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