jiiheee's 개발 일지
[Django] 회원가입 API 구현하기 (2) 본문
회원가입 api를 구현하다 다양한 문제에 봉착했다..
문제
- new_user.save()에서 save 함수가 작동하지 않는것
- accounts/models.py가 user/models.py와 겹치는 부분이 많음
해결
[문제 1번]
orm으로 creat하는 순간 db에 저장하는 것도 함축되어 있으므로 save()는 필요 없음
<기존 views.py>
from django.http import HttpResponse
from accounts.models import Signup
def signup(request):
if request.method == 'POST':
name = request.POST['name']
password = request.POST['password']
phone = request.POST['phone']
mail = request.POST['mail']
new_user = Signup.objects.create(name, password, phone, mail)
new_user.save()
return HttpResponse('회원가입이 완료되었습니다.')
<수정 후 views.py>
from django.http import HttpResponse
from user.models import User
from rest_framework.views import APIView
from user.models import User
class SignUpView(APIView):
def post(self, request):
"""
post 요청에서 데이터를 가져올때 -> request.data.get("컬럼명")
get 요청에서 데이터를 가져올때 -> request.query_params.get("컬럼명")
"""
name = request.data.get("name")
password = request.data.get('password')
phone = request.data.get('phone')
mail = request.data.get('mail')
"""
1. 객체를 만든다음에 save하는 방식
user = User(name=name, password=password, phone=phone, mail=mail)
user.save()
2. 클래스의 ORM을 사용하는 방식
new_user = User.objects.create(name, password, phone, mail)
"""
User.objects.create(
realname=name,
password=password,
phone=phone,
mail=mail,
is_active=True
)
return HttpResponse('회원가입이 완료되었습니다.')
[문제 2번]
accounts/models.py를 주석처리하고 user/models을 사용
# from django.db import models
# class Signup(models.Model):
# name = models.CharField(max_length=200)
# password = models.CharField(max_length=200, default='1234')
# phone = models.CharField(max_length=200)
# mail = models.CharField(max_length=200)
# is_active = models.BooleanField(default=True, null=False)
# create_at = models.DateTimeField(auto_now_add=True)
# update_at = models.DateTimeField(auto_now_add=True)
# class Meta:
# db_table = 'signup'
사실 회원가입할 때 필요한 정보는 곧 DB에 저장되는 정보와 동일하므로 class를 중복해서 사용할 필요가 없다.
= class User 사용
'📚 Study > Django' 카테고리의 다른 글
[Django] 물품 검색 API 구현하기 (0) | 2023.12.14 |
---|---|
[Django] 주문 취소 API 구현하기 (0) | 2023.12.13 |
[Django] 주문 등록 API 구현하기 (0) | 2023.12.13 |
[Django] 주문내역조회 API 구현하기 (0) | 2023.12.12 |
[Django] 회원가입 API 구현하기 (1) (0) | 2023.12.06 |