DRF 10 - UserProfile API

Joey Lee·2020년 7월 13일
0

Django REST Framework

목록 보기
11/16

아래 사례는 Udemy의 "The complete Guide to Django Restframework and Vue JS" 강의 중 Section4 의 : Django REST Framework - Level Three 내용으로서 UserProfile API 작성사례이며, DRF XX편까지 이어집니다.

1. 프로젝트 사전 Set-up

1) profileapi 프로젝트 폴더 내 아래 파일 작성

[settings.py]

INSTALLED_APPS = [ 
     # 기존 APPS 외 아래 추가
    'rest_framework',
    'profiles'
]

MEDIA_URL = '/media/'
MEDIA_ROOT = "uploads"

[urls.py]

from django.conf.urls.static import static
from django.conf import settings

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

2) profile > models.py 작성

from django.db import models

from django.contrib.auth.models import User

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.CharField(max_length=240, blank=True)
    city = models.CharField(max_length=30, blank=True)
    avatar = models.ImageField(null=True, blank=True)

    def __str__(self):
        return self.user.username


class ProfileStatus(models.Model):
    user_profile = models.ForeignKey(Profile, on_delete=models.CASCADE)
    status_content = models.CharField(max_length=240)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name_plural = "statuses"

    def __str__(self):
        return str(self.user_profile)

3) admin.py 작성

from django.contrib import admin
from profiles.models import Profile, ProfileStatus

admin.site.register(Profile)
admin.site.register(ProfileStatus)

4) 모델 migrate 및 어드민 계정 생성

> python manage.py makemigrations
> python manage.py migrate
> python manage.py superusercreate

5) profile > signals.py 추가 후 작성

[signals.py]

from django.contrib.auth.models import User
from django.db.models.signals import post_save  # User 객체가 생성되면 시그널 정보를 전달
from django.dispatch import receiver  # 시그널 정보를 받는 리시버
from profiles.models import Profile

@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
    print("Created:", created)    # 새롭게 객체 생성되면 True, 아니면 False

    if created:
        Profile.objects.create(user=instance)

[apps.py]

from django.apps import AppConfig


class ProfilesConfig(AppConfig):
    name = 'profiles'

    def ready(self):
        import profiles.signals

6) api > serializers.py 작성

from rest_framework import serializers
from profile.models import Profile, ProfileStatus

class ProfileSerialzier(serializers.ModelSerializer):

    user = serializers.StringRelatedField(read_only=True)
    avatar = serializers.ImageField(read_only=True)

    class Meta:
        model = Profile
        fields = "__all__"


class ProfileAvatarSerializer(serializers.ModelSerializer):

    class Meta:
        model = Profile
        fields = ("avatar", )


class ProfileStatusSerializer(serializers.ModelSerializer):

    user_profile = serializers.StringRelatedField(read_only=True)

    class Meta:
        model = Profile
        fields = "__all__"
profile
안녕하세요!

0개의 댓글