[패스트캠퍼스 수강 후기] 파이썬 인강 100% 환급 챌린지 18 회차 미션

2020. 11. 19. 22:56Coding/Python-Fastcampus

728x90

03. View - 02. 회원 가입 만들기

index 페이지 만들기.

base.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<html>
 
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
        integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"
        integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n"
        crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"
        integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
        crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"
        integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6"
        crossorigin="anonymous"></script>
 
</head>
 
<body>
    <div class="container">
        {% block contents %}
        {% endblock %}
    </div>
</body>
 
</html>
cs

 

index.html

1
2
3
4
{% extends "base.html" %}
{% block contents %}
Hello World!
{% endblock %}
cs

 

urls.py

1
2
3
4
5
6
7
8
9
from django.contrib import admin
from django.urls import path
from fcuser.views import index
 
urlpatterns = [
    path('admin/', admin.site.urls),
    path('', index),
]
 
cs

 

 

아무 페이지도 없는 상황이니,

기본이되는 base.html과 index.html을 만들어준다.

 

urls.py에 등록해서 "Hello World!" 잘 뜨는것까지 확인하면 완료.


회원가입 페이지 만들기.

forms.py 생성.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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='비밀번호 확인'
    )
cs

 

register.html.

1
2
3
4
{% extends "base.html" %}
{% block contents %}
Register {{ form }}
{% endblock %}
cs

 

 

views.py에서 연결.

1
2
3
4
5
6
7
8
9
10
11
12
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
cs

 

urls.py에 등록.

1
2
3
4
5
6
7
8
9
from django.contrib import admin
from django.urls import path
from fcuser.views import index, RegisterView
 
urlpatterns = [
    path('admin/', admin.site.urls),
    path('', index),
    path('register/', RegisterView.as_view()),
]
cs

RegisterView는 Class이므로 .as_view()를 써줘야한다.

 

 

실행.

 

 


기존에 만든 fc_community를 참고해서 register.html과 forms.py를 만들자.

register.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
{% 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 %}
                {% 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 }}" 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 %}
 
cs

 

forms.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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()
        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''비밀번호가 다릅니다.')
cs

 

 

 

fc_community때와 다르게 class를 이용해서 만드니 코드가 훨씬 줄었다.

 

 


회원가입.

forms.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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='비밀번호 확인'
    )
 
    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(
                    email=email,
                    password=password
                ).save()
 
cs

 

 

정상적으로 회원가입까지 완료.

 

 


05. 흐름 제어 - 06. 반복문 - 퀴즈 및 풀이(1)

1
2
3
4
5
6
7
8
9
# 2. 아래 딕셔너리에서 '사과'가 포함되었는지 확인하세요.
q2 =  {"봄""딸기""여름""토마토""가을""사과"}
 
for k in q2.keys() :
    if q2[k] == "사과" :
        print('사과가 포함되어있습니다.')
        break
else :
    print('사과가 없습니다.')
cs

for-else 문이 재미있어서 첨부.

 

 


05. 흐름 제어 - 07. 반복문 - 퀴즈 및 풀이(2)

리스트안에서 for문 사용.

1
2
numbers = [x for x in range(1,101)]
print(numbers)
cs

짧게 줄여쓰고 직관적으로 보기 편함.

 

 

나머지는 다 다른 언어들과 같은 방식이라 넘어감.

 

 

 

 

 

 

 

 

올인원 패키지 : 파이썬 웹 개발👉https://bit.ly/33a7nvc

728x90