본문 바로가기

python + Django

회원가입 해보기

● 새로운 app등록 

1. manage.py startapp 앱명칭 을 통해서 새로운 앱을 생성

2. settings.py 에 새로운 앱을 등록하고 urls.py 및 views.py에 회원가입 html경로 설정

3. 새로운 앱 폴더아래에 templates 폴더를 생성하고 그안에 회원가입 html생성

4. html에 간단한 form을 설정하고  {% csrf_token %} 을 설정

  ** django보안 설정상 {% csrf_token %} 을 입력하지 않으면 form 에서 submit이 진행되지 않는다.


● 유저 생성

: Django에서는 유저 생성, 권한부여 같은 기능 ( create_user() )기본적으로제공하고 있다.

views.py에 아래의 코드를 입력한다.

>>> from django.contrib.auth.models import User
>>> user = User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword')

# At this point, user is a User object that has already been saved
# to the database. You can continue to change its attributes
# if you want to change other fields.
>>> user.last_name = 'Lennon'
>>> user.save()

from 에서 입력한 정보들은 request.POST["id"] 형태로 전달받게 되는데 input 에 name 과  ["id"] 부분을 일치 맵핑시켜 주면 해당 정보를 

넘겨받을 수 있다.


save() 함수를 통해서 DataBase 에 저장.


* 참고 : https://docs.djangoproject.com/en/2.1/topics/auth/default/



● 예외처리

: Django 에서는 여러가지 예외처리에 대한 부부을 지원하고 있다.

예제는 get() 함수에 대한 예외처리 부분으로 정리한다.

** get() : Database에서 결과를 조회하는 함수  >> sql에서 select와 비슷한 기능을 한다고 판단됨


아래 코드를 통해서 예외처리를 진행할 수 있다.

from django.core.exceptions import ObjectDoesNotExist
try:
    e = Entry.objects.get(id=3)
    b = Blog.objects.get(id=1)
except ObjectDoesNotExist:
    print("Either the entry or blog doesn't exist.")


* 해당 부분까지 완료한 상태 코드

from django.http import HttpResponse

from django.shortcuts import render

from django.views import View

from django.contrib.auth.models import User

from django.core.exceptions import ObjectDoesNotExist


# Create your views here.


class signIn(View):

    def get(self, request, *args, **kwargs):    # get 요청이 들어온 경우

        return render(request, 'signIn.html')

    def post(self, request, *args, **kwargs):   # post 요청이 들어온 경우

        id = request.POST["id"]

        password = request.POST["password"]

        email = request.POST["email"]


        response = HttpResponse("insert fail")


        try:

            User.objects.get(username=id)# 입력한 아이디가 이미 등록되있는지 확인 조회되면 중복아이디가 있는것으로 간주하고 등록 실패

            return response

        except ObjectDoesNotExist:

            response = HttpResponse("save")

            user = User.objects.create_user(id, email, password)

            user.save()

            return response




'python + Django' 카테고리의 다른 글

제너릭 뷰  (0) 2019.02.03
settings.py 알아보기  (0) 2019.02.03
Mysql 연동하기  (0) 2019.01.27
mod_wsgi 설치(Django 설정하기_2)  (0) 2019.01.23
apache 설정 (Django 연동을 위한 준비)  (0) 2019.01.20