Django2 (5. 회원 가입 만들기) feat.페스트캠퍼스

min seung moon·2021년 3월 15일
0

Django

목록 보기
21/37
post-thumbnail

1. fcuser부터 작업하기!

01. fcuser의 views.py 수정하기!

from django.shortcuts import render

# Create your views here.


def index(request):
    return render(request, 'index.html')

02. fcuser에 templates 폴더를 만들고 base.html, index.html 생성

03. base.html 수정!

<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=divice-width, inital-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-b5kHyXgcpbZJO/tY9Ul7kGkf1S0CWuKcCD38l8YkeH8z8QjE0GmW1gYU5S9FOnJ0" crossorigin="anonymous">
    </script>
</head>
<div class="container">
    {% block contents %}
    {% endblock %}
</div>

</html>

bootstrap, https://getbootstrap.com/docs/5.0/getting-started/introduction/

04. index.html 수정!

{% extends "base.html" %}
{% block contents %}
Hello world!
{% endblock %}

05. root폴더의 urls.py에 index.html 연결하기!

"""fc_django URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from fcuser.views import index

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', index)
]


06. fcuser에 forms.py 만들고 입력하기!

from django import forms


class RegisterForm(forms.Form):
    email = forms.EmailField(
        error_messages={
            'required': '이메일을 입력해주세요.'
        },
        max_length=64, label='이메일'
    )
    password = forms.CharField(
        error_messages={
            'required': '비밀번호를 입력해주세요'
        },
        widget=forms.PasswordInput, label='비밀번호'
    )
    re_password = forms.CharField(
        error_messages={
            'required': '비밀번호를 입력해주세요'
        },
        widget=forms.PasswordInput, label='비밀번호 확인'
    )

07. fciser에 views.py 수정하기!

from django.shortcuts import render
from django.views.generic.edit import FormView
from .forms import RegisterForm
# Create your views here.


# index.html 연결 뷰
def index(request):
    return render(request, 'index.html')


class RegisterView(FormView):
    # html file
    template_name = 'register.html'
    # forms.py에 있는 forms
    form_class = RegisterForm
    # 정상적으로 값이 처리가 되었을 때 url이동
    success_url = '/'

08. template에 register.html 생성 입력!

{% extends "base.html" %}
{% block contents %}
Register
{% endblock%}

09. root 폴더 urls.py 수정!

from django.contrib import admin
from django.urls import path
from fcuser.views import index, RegisterView

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', index),
    # class는 .as_view()를 입력!
    path('register/', RegisterView.as_view()),
]


10. fcuser에 register.html 수정!

{% extends "base.html" %}

{% block contents %}
<div class="row mt-5">
    <div class="col-12 text-center">
        <h1>회원가입</h1>
    </div>
</div>
<div class="row mt-5">
    <div class="col-12">
        {{ error }}
    </div>
</div>
<div class="row mt-5">
    <div class="col-12">
        <form method="POST" action=".">
            {% csrf_token %}
            <!-- 커스터마이징 -->
            <!-- form을 반복문에 넣으면 각 필드별로 나온다 -->
            {% for field in form %}
            <div class="form-group">
                <label for="{{ field.id_for_label}}">{{field.label}}</label>
                <input type="{{field.field.widget.input_type}}" class="form-control" id="{{ field.id_for_label}}"
                    placeholder="{{field.label}}" name="{{field.name}}" />
            </div>
            {% if field.errors %}
            <span style="color: red;">{{ field.errors }}</span>
            {% endif %}
            {% endfor %}
            <button type="submit" class="btn btn-primary">회원가입</button>
        </form>
    </div>
</div>
{% endblock %}

11. forms.py 수정하기!

from django import forms


class RegisterForm(forms.Form):
    email = forms.EmailField(
        error_messages={
            'required': '이메일을 입력해주세요.'
        },
        max_length=64, label='이메일'
    )
    password = forms.CharField(
        error_messages={
            'required': '비밀번호를 입력해주세요'
        },
        widget=forms.PasswordInput, label='비밀번호'
    )
    re_password = forms.CharField(
        error_messages={
            'required': '비밀번호를 입력해주세요'
        },
        widget=forms.PasswordInput, label='비밀번호 확인'
    )

    def clean(self):
        cleaned_data = super().clean()
        password = cleaned_data.get('password')
        re_password = cleaned_data.get('re_password')

        if password and re_password:
            if password != re_password:
                self.add_error('password', '비밀번호가 서로 다릅니다.')
                self.add_error('re_password', '비밀번호가 서로 다릅니다.')


def vs class

12. forms.py 회원가입 DB에 입력하기!

from django import forms
from .models import Fcuser


class RegisterForm(forms.Form):
    email = forms.EmailField(
        error_messages={
            'required': '이메일을 입력해주세요'
        },
        max_length=64, label='이메일'
    )
    password = forms.CharField(
        error_messages={
            'required': '비밀번호를 입력해주세요'
        },
        widget=forms.PasswordInput, label='비밀번호'
    )
    re_password = forms.CharField(
        error_messages={
            'required': '비밀번호를 입력해주세요'
        },
        widget=forms.PasswordInput, label='비밀번호확인'
    )

    # validate
    def clean(self):
        cleaned_data = super().clean()
        email = cleaned_data.get('email')
        password = cleaned_data.get('password')
        re_password = cleaned_data.get('re_password')

        if password and re_password:
            if password != re_password:
                self.add_error('password', '비밀번호가 서로 다릅니다')
                self.add_error('re_password', '비밀번호가 서로 다릅니다')
            else:
                fcuser = Fcuser(
                    email=email,
                    password=password
                )
                fcuser.save()

13. 실행해보기!


profile
아직까지는 코린이!

0개의 댓글

관련 채용 정보