MY MEMO
[IONIC+Django] api를 이용해 데이터 가져오기 본문
Django 설치 : http://dlwodus.tistory.com/365
Ionic 설치 : http://dlwodus.tistory.com/366
Django 서버를 돌리고 (localhost) Ionic 을 돌린다 (localhost)
Django의 api를 얻어서 Ionic에서 받아온다!
1. 위의 설치법과 같은 설치했으면 아래와 비슷하게 생성된다.
+) Django Rest Framework ImageField 이용하기 : https://cjh5414.github.io/django-rest-framework-imagefield/
* models.py : Database를 정의
Database를 생성했을 때
from django.conf import settings
from django.db import models
# Create your models here.
class BlogPost(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
title = models.CharField(max_length=120, null=True, blank=True)
content = models.TextField(max_length=120, null=True, blank=True)
timestamp = models.DateField(auto_now_add=True)
def __str__(self):
return str(self.user)
# image를 저장하는 Database
class Person(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
image = models.ImageField(default='media/coding.jpeg')
python3 manage.py makemigrations
python3 manage.py migrate
를 해줘야 적용됨
생성되면 위와 같이 migrations 폴더 아래에 생성된 0001~~ 파일 생성
* api/serializers.py : Database를 json형식으로 만들 때 json형태를 만듬
from rest_framework import serializers
from api.models import BlogPost
from api.models import Person
class BlogPostSerializers(serializers.ModelSerializer):
class Meta:
model = BlogPost
fields = [
'pk',
'user',
'title',
'content',
]
class PersonSerializer(serializers.HyperlinkedModelSerializer):
image = serializers.ImageField(use_url=True)
class Meta:
model = Person
fields = ('first_name', 'last_name', 'image')
* api/views.py : //잘모름
from rest_framework import generics
from api.models import BlogPost
from api.models import Person
from .serializers import BlogPostSerializers
from .serializers import PersonSerializer
class BlogPostRudView(generics.RetrieveUpdateDestroyAPIView):
lookup_field = 'pk'
serializer_class = BlogPostSerializers
# queryset = BlogPost.objects.all()
def get_queryset(self):
return BlogPost.objects.all()
class PeopleListView(generics.ListCreateAPIView):
queryset = Person.objects.all()
serializer_class = PersonSerializer
def perform_create(self, serializer):
serializer.save()
* api/urls.py : url을 정의하는 것
from .views import BlogPostRudView
from .views import PeopleListView
from django.conf.urls import url
urlpatterns = [
url(r'^(?P<pk>\d+)/$', BlogPostRudView.as_view(), name='post-rud'),
url(r'people', PeopleListView.as_view(), name='people-list')
]
* Tour/urls.py : url앞의 패턴을 정의
"""Tour URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin
# Medua 추가를 위한 import
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/test/', include('api.api.urls', namespace='api-test'))
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Django의 setting과 database까지 완벽하면 api가 만들어진 것이다!
127.0.0.1:8000/admin : Database를 볼 수 있음 (Django 환경 설치 에 나와있음)
127.0.0.1:8000/api/test/1 : api/test/primary_key는 BlogPost의 primary_key 데이터를 가져옴
127.0.0.1:8000/api/test/people : people은 image와 first_name, last_name을 json형식으로 볼 수 있음
2. Ionic에서!
ionic start application_이름 tabs
providers/apitest에서 Django의 api를 가져올 것이다
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';
/*
Generated class for the ApitestProvider provider.
See https://angular.io/guide/dependency-injection for more info on providers
and Angular DI.
*/
@Injectable()
export class ApitestProvider {
api_id;
url;
constructor(public http: HttpClient) {
console.log('Hello ApitestProvider Provider');
this.url = 'http://localhost:8000/api/test/1/'
}
getApi(api_id){
return this.http.get(this.url+'?format=json')
}
getImage(api_id){
return this.http.get('http://localhost:8000/api/test/people/'+api_id+'?format=json')
}
}
그렇다면 가져온 Data를 Ionic에 적용한다
home.ts
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { ApitestProvider } from '../../providers/apitest/apitest';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
api_id : any;
api : any;
image : any;
constructor(public navCtrl: NavController, private apitest : ApitestProvider) {
}
ionViewWillEnter(){
this.api_id = '1'
this.apitest.getApi(this.api_id).subscribe(api => {
console.log(api);
this.api = api;
});
this.apitest.getImage(this.api_id).subscribe(api=>{
console.log(api);
this.image = api;
});
}
}
두개의 데이터를 가져와서 this.변수에 넣는다
home.html
<ion-header>
<ion-navbar>
<ion-title>Home</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<ion-grid *ngFor="let img of image;">
<h1>{{img.first_name}}{{img.last_name}}</h1>
<img style="height:150px; width:150px" src="{{img.image}}">
</ion-grid>
<h2>Welcome to Ionic!</h2>
<p>
안녕하세요~~
</p>
<ion-item>
<ion-label floating>아이디</ion-label>
<!-- <ion-input type="password" #password></ion-input>-->
<ion-input type="text"></ion-input>
</ion-item>
</ion-content>
*ngFor문은 data가 ArrayList일 때 사용한다
현재 img.image는 image주소이기 때문에 <img src=안에 넣어준다
그렇다면 실행해보자!
Django 실행
python3 manage.py runserver
Ionic 실행
ionic serve
두개 실행 후 chrome에서 개발자 모드 > console에서 api가 들어온 것을 확인하면 된다!!!
'STUDYING > APPLICATION' 카테고리의 다른 글
[IONIC+Django] 로그인, 회원가입을 위한 Token Authentication (0) | 2018.01.28 |
---|---|
[IONIC] ionic 설치하기 (0) | 2018.01.16 |
[ANDROID] 안드로이드에서 MAVEN 추가 (MAC) (0) | 2017.12.05 |
[ANDROID] ListView 만들기 (0) | 2017.12.03 |