본문 바로가기

Django Basics

[패스트캠퍼스 수강 후기] 파이썬 인강 자기계발 챌린지 31 회차 미션

패스트캠퍼스 파이썬 웹개발 올인원 패키지 후기(31)

파이썬 웹개발 올인원 패키지 31 일차 후기 겸 학습기록 입니다.

 

어제에 이어 오늘은 회원 정보 모델 클래스에 필드를 하나 더 추가 해보겠씁니다.

그리고 static 파일이 무엇인지? 어떻게 관리하는지? 공부를 하고,

웹 개발에 있어 중요한 개념 중 하나인 세션에 대해서도 알아보았습니다.

 

먼저 회원에 필드 추가하는 부분 부터 정리하겠습니다.

 

 

MTV - 회원에 필드 추가하기

fcuser/models.py

from django.db import models

# Create your models here.

class Fcuser(models.Model):
    username = models.CharField(max_length=64, verbose_name="사용자명")
    useremail = models.EmailField(max_length=128, verbose_name="사용자 이메일")
    password = models.CharField(max_length=64, verbose_name="비밀번호")
    registered_dttm = models.DateTimeField(auto_now_add=True, verbose_name="등록시간")

    def __str__(self):
        return self.username

    class Meta:
        db_table = 'fastcampus_fcuser'
        verbose_name = '패스트캠퍼스 사용자'
        verbose_name_plural = '패스트캠퍼스 사용자'

 

fcuser/templates/register.html

<html>
    <head>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
        <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" 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.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
    </head>
    <body>
        <div class="cotainer">
            <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 %}
                        <div class="form-group">
                          <label for="username">사용자 이름</label>
                          <input type="text" class="form-control" id="username" placeholder='사용자이름' name="username">
                        </div>
                        <div class="form-group">
                            <label for="useremail">사용자 이메일</label>
                            <input type="email" class="form-control" id="useremail" placeholder='사용자이메일' name="useremail">
                          </div>
                        <div class="form-group">
                          <label for="password">비밀번호</label>
                          <input type="password" class="form-control" id="password" placeholder="비밀번호" name="password">
                        </div>
                        <div class="form-group form-check">
                          <label for="re-password">비밀번호 확인</label>
                          <input type="password" class="form-control" id="re-password" placeholder="비밀번호 확인" name="re-password">
                        </div>
                        <button type="submit" class="btn btn-primary">등록</button>
                    </form>
                </div>
            </div>
        </div>
    </body>
</html>

 

fcuser/views.py

from django.http import HttpResponse
from django.shortcuts import render
from django.contrib.auth.hashers import make_password
from .models import Fcuser


def register(request):
    if request.method == 'GET':
        return render(request, "register.html")
    elif request.method == 'POST':
        username = request.POST.get('username', None)
        useremail = request.POST.get('useremail', None)
        password = request.POST.get('password', None)
        re_password = request.POST.get('re-password', None)

        res_data = {}

        if not (username and password and re_password and useremail):
            res_data['error'] = '모든 값을 입력해야 합니다.'
        elif password != re_password:
            res_data['error'] = "비밀번호가 다릅니다."
        else:
            fcuser = Fcuser(
                username=username,
                useremail=useremail,
                password=make_password(password)
            )
            fcuser.save()

        return render(request, 'register.html', res_data)

 

static 파일 관리하기( +CDN  소개)

CDN(콘텐츠 배달 네트워크)

사용자에게 웹 콘텐츠를 효율적으로 제공할 수 있는 서버의 분산 네트워크

글로벌 서비스를 하게 될때 필요하다. > 각 나라별로 콘텐츠가 뿌려져 있다. > 사용자에게 가장 가까운 곳으로 가서 콘텐츠를 받아오게 된다.

 

Static 세팅

1. fc_community/static 폴더 생성

2. fc_community/fc_community/settings.py 에 아래내용 추가

STATICFILES_DIRS = [

    os.paht.join(BASE_DIR, 'static')

]

3. fcuser/register.html 수정 > head 부분에 아래 내용 추가, bootstrap.min.css 는 bootstrap 무료 테마파일을 다운받은 것임.

 <head>

        <link rel="stylesheet" href="/static/bootstrap.min.css" />

 

로그인 - 세션이란

세션(Session)과 쿠키(Cookie)

클라이언트(웹브라우저)에는 Cookie(저장공간)가 있다.

Cookie를 활용해서 어떠한 데이터를 유지하는 것

  1. 일단 클라이언트에서 서버에 접속하여 리퀘스트 한다.
  2. 서버는 응답 헤더에 Cookie 정보(해당 클라이언트 만의 키)를 넣어서 응답한다.
  3. 클라이언트는 해당 Cookie(서버로 부터 받은 자기만의 키도 포함)를 자기 저장소에 저장한다.(이때 각 웹사이트 별로 나누어서 저장)
  4. 다음 리퀘스트부터는 클라이언트가 해당 Cookie를 포함해서 리퀘스트한다.
  5. 서버는 해당 Cookie 정보를 보고 클라이언트를 구별해서 인지할 수 있게 된다.

 

 

 

패스트캠퍼스 파이썬 인강 자세한 내용은 아래 링크를 참고해 주세요!

 

https://bit.ly/2WG0IXN