Project /setting.py
"""
Django settings for todo_app project.
Generated by 'django-admin startproject' using Django 2.2.6.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '%@^^)=9unpeft2e^)p!qlwsj__69z9laq^@i1f8f7-kadjr$2)'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'todo.apps.TodoConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'corsheaders',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.locale.LocaleMiddleware',
'corsheaders.middleware.CorsMiddleware',
]
ROOT_URLCONF = 'todo_app.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'todo_app.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
# }
'default':{
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'todo',
'USER': 'dell',
'PASSWORD': 'dell0212',
'HOST': '10.0.75.1',
'PORT': '5432',
}
}
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
Project /urls.py
from django.conf.urls import url, include
from django.contrib import admin
# from django.urls import path
from todo.urls import router as todo_router
urlpatterns = [
# path('admin/', admin.site.urls),
url(r'^admin/', admin.site.urls),
url(r'^api/', include(todo_router.urls)),
]
App /urls.py
from rest_framework import routers
from .views import ToDoViewSet
router = routers.DefaultRouter()
router.register(r'todo', ToDoViewSet)
App /views.py
from django.shortcuts import render
import django_filters
from rest_framework import viewsets, filters
from .models import ToDo
from .serializer import ToDoSerializer
from rest_framework.decorators import api_view
class ToDoViewSet(viewsets.ModelViewSet):
queryset = ToDo.objects.all().order_by('-updated_at')
serializer_class = ToDoSerializer
App /models.py
from django.db import models
class ToDo(models.Model):
title = models.CharField(max_length=140, blank=False)
created_at = models.DateTimeField(auto_now=True)
updated_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
App /serializer.py
from rest_framework import serializers
from .models import ToDo
class ToDoSerializer(serializers.ModelSerializer):
class Meta:
model = ToDo
fields = ('id', 'title', 'created_at', 'updated_at')
todo.service.ts
import { Injectable } from "@angular/core";
// import { Http, Headers } from '@angular/http'; これは非推奨になった
import { HttpClient, HttpHeaders } from '@angular/common/http';
//import 'rxjs/add/operator/toPromise';
import { Todo } from '../models/todo.model';
@Injectable()
export class TodoService {
todo: Todo[] = [];
private Url = `http://localhost:8000/api/todo/`
private headers = new HttpHeaders({'Content-Type': 'application/json'});
constructor(private http: HttpClient){
this.setAuthorization('my-auth-token');
}
private strData: string[];
// 全てのtodoをGETする
getAllTodo(): Promise {
return this.http
.get(this.Url)
.toPromise()
.then((res) => {
const response: any = res;
return response;
})
// .then(response => response.json() as Todo[])
.catch(this.errorHandler)
}
create(todo: Todo): Promise{
return this.http
.post(this.Url, JSON.stringify(todo), {headers: this.headers})
.toPromise()
.then((res) => {
const response: any = res;
return response;
})
// .then(res => res.json())
.catch(this.errorHandler)
}
getNewTodo(): Promise{
return this.http
.get(this.Url+"?limit=1")
.toPromise()
.then((res) => {
const response: any = res;
return response;
})
//.then(res => res.json().results)
.catch(this.errorHandler)
}
delete(id: number): Promise{
const url = `${this.Url}${id}/`;
return this.http
.delete(url, {headers: this.headers})
.toPromise()
.then((res) => null)
.catch(this.errorHandler)
}
update(todo: Todo): Promise{
const url = `${this.Url}${todo.id}/`;
return this.http
.put(url, JSON.stringify(todo), {headers: this.headers})
.toPromise()
.then((res) => {
const response: any = res;
return response;
})
.catch(this.errorHandler)
}
private errorHandler(err) {
console.log('Error occured.', err);
return Promise.reject(err.message || err);
}
public setAuthorization(token: string = null): void {
if (!token) {
return;
}
const bearerToken: string = `Bearer ${token}`;
//this.httpOptions.headers = this.httpOptions.headers.set('Authorization', bearerToken);
}
}
todo-list.component.ts
import { Component,Input } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { TodoService } from '../services/todo.service';
import { Todo } from '../models/todo.model';
@Component({
selector: 'todo-list',
templateUrl: '../templates/todo-list.component.html',
styleUrls: ['../static/todo-list.component.css']
})
export class TodoListComponent {
todos: Todo[] = [];
newtodos: Todo[] = []; //追記
@Input() todo: Todo = new Todo(); //追記
constructor(private todoService: TodoService,){}
ngOnInit(): void {
this.todoService.getAllTodo()
.then(todos => this.todos = todos);
}
save(): void {
this.todoService
.create(this.todo)
.then(data => {this.getNewTodo()});
this.todo = new Todo();
}
delete(id): void {
this.todoService
.delete(id);
}
update(id: number, title: string): void {
let todo = {
id: id,
title: title
}
this.todoService.update(todo);
}
// 最新の一件を呼び出す挙動
getNewTodo(): void {
this.todoService
.getNewTodo()
.then(res => {this.pushData(res)});
}
// htmlに渡すnewtodosにデータをpushする
pushData(data: Todo): void {
this.newtodos.unshift(data);
}
}
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { TodoListComponent } from './components/todo-list.component';
import { TodoService } from './services/todo.service';
// @NgModule({
// declarations: [
// AppComponent
// ],
// imports: [
// BrowserModule,
// AppRoutingModule
// ],
// providers: [],
// bootstrap: [AppComponent]
// })
@NgModule({
declarations: [
AppComponent,
TodoListComponent,
],
imports: [
BrowserModule,
FormsModule,
HttpClientModule,
AppRoutingModule
],
providers: [TodoService],
bootstrap: [AppComponent]
})
export class AppModule { }
app-routing.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { TodoListComponent } from './components/todo-list.component';
import { TodoService } from './services/todo.service';
// @NgModule({
// declarations: [
// AppComponent
// ],
// imports: [
// BrowserModule,
// AppRoutingModule
// ],
// providers: [],
// bootstrap: [AppComponent]
// })
@NgModule({
declarations: [
AppComponent,
TodoListComponent,
],
imports: [
BrowserModule,
FormsModule,
HttpClientModule,
AppRoutingModule
],
providers: [TodoService],
bootstrap: [AppComponent]
})
export class AppModule { }