본문 바로가기
Django

Django signup 세부구현

by nyanguk 2021. 1. 26.

이전에 만든 회원가입, 로그인, 로그아웃을 세부적으로 구현해보고자 한다. 

 

회원가입 세부구현

  • 이미 존재하는 아이디일 경우 오류메세지를 띄우고 다시 회원가입 페이지로 돌아가기
  • 회원가입 시 1차,2차 비밀번호가 다르면 오류페이지 띄우고 다시 회원가입 페이지로 돌아가기

두가지 모두 오류 페이지를 띄운다음 특정 시간동안 머무른 후 다시 회원가입 페이지로 돌아가도록 수정해보자

HTML의 meta - refresh속성 사용하면 특정 시간동안 대기한 뒤 특정 페이지로 이동시킬수 있다. body 부분에 추가되어야 한다.

base.html의 body 부분에 block추가하기

body안에 추가될 코드이므로 base.html을 기본 템플릿으로 사용하고 있다면 조금은 곤란해진다.

현재 base.html 에는 post라는 block만 존재한다. 하지만 오류페이지를 띄우는 것은 post 기능과는 매우 다르므로 새로운 block을 만들어야 한다.

 

post 블록 바로 밑에 아래 코드를 추가해준다.

블록의 이름이 무엇이든 상관 없다. 다만  error.html 을 만들때 사용하기 때문에 잘 기억하자!

{% block page %}
{% endblock %}

아래 코드와 같은 위치에 추가해주면 된다.

<!-- blog/templates/blog/base.html -->
{% load static %}
<html>
    <head>
        <link href="https://fonts.googleapis.com/css2?family=Yeon+Sung&display=swap" rel="stylesheet">
        <link href="https://fonts.googleapis.com/css2?family=Do+Hyeon&family=Roboto&display=swap" rel="stylesheet">
        <link rel="stylesheet" href="{% static 'css/blog.css' %}">
        <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
        <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
        <title>nyanguk의 Django 튜토리얼</title>
    </head>
    <body>
        <div class = title-1>
            <a href="{% url 'post_draft_list' %}" class="top-menu"><span class="glyphicon glyphicon-edit"></span></a>
            <a href="{% url 'post_new' %}" class="top-menu"><span class="glyphicon glyphicon-plus"></span></a>
            <a href="{% url 'signup' %}" class="top-menu"><span class="glyphicon glyphicon-user"></span></a>
            <a href="{% url 'login' %}" class="top-menu"><span class="glyphicon glyphicon-ok"></span></a>
            <h1> <a href="http://127.0.0.1:8000/">nyanguk의 블로그</a></h1>
        </div>
        <div class = post>
            {% block content %}
            {% endblock %}
        </div>
        <div class = swap>
            {% block page %}
            {% endblock %}
        </div>
    </body>
</html>

 

error.html 생성하기

HTML의 meta - refresh속성을 사용한다.

여러분들이 수정해야할 부분은  content 이다 "대기시간 ; 이동할 페이지의 url" 이때 태그 url을 이용하면 하드코딩된 url을 사용하지 않을뿐더러 복잡한 url을 단번에 구별 해낼수 있다.

<meta http-equiv="refresh" content="5; {% url 'signup' %}">

여기서 중요한 점은 회원가입시 발생할 수 있는 오류는 총 3가지라는 점이다. 각 오류가 발생할때마다 다른 html을 불러오기에는 오류가 많아질 수록 많은 파일이 요구되기 때문에 적절하지 못하다. 

그래서 err 라는 변수를 전달받아 그 값에따라 어떤 오류 메세지를 띄울 것인지 결정한다.

 

완성된 error.html을 확인하자

{% extends 'blog/base.html' %}

{% block page %}
    <h4>회원가입에 오류가 발생하였습니다 5초후 회원가입페이지로 돌아갑니다.</h4>
    {% if err == 0 %} 
        <p> 중복된 아이디가 존재합니다 </p>
    {% elif err == 1 %}
        <p> 1차 비밀번호와 2차 비밀번호가 다릅니다. </p>
    {% endif %}
    <meta http-equiv="refresh" content="5; {% url 'signup' %}">
{% endblock %}

 

error 코드를 넘기기 위한 views.py 수정

위에서 발생한 오류에 따라 err 값이 변경되도록 views.py 를 수정하자

 

중복아이디는 filter를 통해 데이터베이스에 전달된 userId와 동일한 username을 검사한다. 만약 존재하면 쿼리셋을 반환한다면 참이 되므로 err 값을 세팅할 수 있다.

각  err코드를 가지고 error.html으로 이동시키려면 아래와 같이 코드를 작성해야한다.

render(request, 'accounts/error.html',{'err':err})
# 회원 가입
def signup(request):
    if request.method == 'POST':
        if User.objects.filter(username=request.POST['userId']).values(): # 이미 아이디가 있다면
            err = 0
            return render(request, 'accounts/error.html',{'err':err})
        else:
            if request.POST['userPw'] == request.POST['confirm']:
                user = User.objects.create_user(username=request.POST['userId'], password=request.POST['userPw'])
                auth.login(request, user)
                return redirect('post_list')
            else: # 1차,2차 비밀번호가 다르다면
                err = 1
                return render(request, 'accounts/error.html',{'err':err})
    return render(request, 'accounts/signup.html')