Django 2(6.ログインの作成)feat.鼠疫キャンパス

17109 ワード

ログインを作成します。


fcuserを表示します。py入力!

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


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


class RegisterView(FormView):
    template_name = 'register.html'
    form_class = RegisterForm
    success_url = '/'

class LoginView(FormView):
    template_name = 'login.html'
    form_class = LoginForm
    success_url = '/'

02.fcuserログイン。htmlの作成と入力!

{% extends "base.html" %}

{% block contents %}
<div class="row mt-5">
    <div class="col-12 text-center">
        <h1>로그인</h1>
    </div>
    <div class="row mt-5">
        <div class="col-12">
            {{ error }}
        </div>
        <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>
</div>
{% endblock %}

03.fcuserのforms。py入力!

from django import forms
from django.contrib.auth.hashers import check_password, make_password
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='비밀번호 확인'
    )

    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=make_password(password)
                )
                fcuser.save()


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

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

        if email and password:
            try:
                fcuser = Fcuser.objects.get(email=email)
            except Fcuser.DoesNotExist:
                self.add_error('email', '이메일이 없습니다')
                return

            if not check_password(password, fcuser.password):
                self.add_error('passwrod', '비밀번호가 틀렸습니다')
            else:
                self.user_id = fcuser.id


04. views.pyを修正!

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


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


class RegisterView(FormView):
    template_name = 'register.html'
    form_class = RegisterForm
    success_url = '/'


class LoginView(FormView):
    template_name = 'login.html'
    form_class = LoginForm
    success_url = '/'

05.ルートフォルダのurls。py接続!

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

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

実行してみます!





07.fcuserを表示します。pyでのセッションの実装

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


# index.html 연결 뷰
def index(request):
    return render(request, 'index.html', {'email': request.session.get('user')})


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


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

    # 유효성 검사가 끝났을 때, 로그인이 정상적으로 되었을 때
    def form_valid(self, form):
        self.request.session['user'] = form.email

        return super().form_valid(form)

08.fcuserのindex。htmlの変更



09. index.htmlにメールを送信!(views.py)



10. forms.尹秀晶。

from django import forms
from .models import Fcuser
from django.contrib.auth.hashers import check_password, make_password


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=make_password(password)
                )
                fcuser.save()


class LoginForm(forms.Form):
    email = forms.EmailField(
        error_messages={
            'required': '이메일을 입력해주세요'
        },
        max_length=64, label='이메일'
    )
    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')

        if email and password:
            try:
                fcuser = Fcuser.objects.get(email=email)
            except Fcuser.DoesNotExist:
                self.add_error('email', '아이디가 없습니다')
                return
            if not check_password(password, fcuser.password):
                self.add_error('password', '비밀번호를 틀렸습니다')
            # 비밀번호가 맞았을 때
            else:
                # 성공한 지점
                # form객체 안에 email attribute key전달
                # 이곳에 입력한것이 views.py {'email': request.session.get('user')})이렇게 사용가능
                self.email = fcuser.email

11.スタート!