Django 5일차 TIL

김민지·2023년 9월 3일
0

Django

목록 보기
5/11

CreateView를 통한 회원가입 구현

class base view 만들기

class AccountCreateView(CreateView):
    model = User
    form_class = UserCreationForm
    success_url = reverse_lazy('accountapp:hello_world')
    template_name = 'accountapp/create.html'

model: 무슨 모델을 사용할 것인지, 장고에서 기본으로 제공하는 User 사용

form_class: User model를 만드는데 필요한 form 생성, 장고에서 기본으로 제공하는 form 사용

success_url:

  • reverse와 reverse_lazy의 차이점
    함수와 클래스의 방식의 차이때문에 함수형 뷰에선 reverse를 사용하고, 클래스형 뷰에서는 reverse_lazy를 사용한다.

template_name: 회원가입 시 사용되는 form, accoount앱 내에서 create.html

➡️ 클래스를 기반으로 한 뷰가 함수형 뷰보다 간단하다.

경로 지정하기

path('create/', AccountCreateView.as_view(), name='create'),

template 작성

{% extends 'base.html' %}

{% block content %}

    <div>
        <form action="{% url 'accountapp:create' %}" method="post">
            {% csrf_token %}
            {{ form }}
            <input type="submit" class="btn btn-primary">
        </form>

    </div>

{% endblock %}

csrf_token은 장고에서 제공하는 기본 보안 시스템

{{ form }}은 form class에서 지정한 형태를 그대로 불러온다.

form_class = UserCreationForm

Login / Logout 구현

url.py
장고에서 기본 제공하는 User를 사용하여 경로를 지정한다.

    path('login/', LoginView.as_view(template_name='accountapp/login.html'), name='login'),
    path('logout/', LogoutView.as_view(), name='logout'),

Redirect Mechanism


1. post, get 파리미터에서 next라는 이름을 가진 value를 찾는다.
2. next가 존재하지 않는다면, Login_redirect_url의 경로로 간다.
3. Login_redirect_url가 존재하지 않는다면, 최종적으로 Default로 전송한다.

{% if not user.is_authenticated %}
        <a href="{% url 'accountapp:login' %}?next={{ request.path }}">
            <span>login</span>
        </a>
        {% else %}
        <a href="{% url 'accountapp:logout' %}?next={{ request.path }}">
            <span>logout</span>
        </a>
        {% endif %}

Bootstrap을 이용한 Form 디자인 정리

부트스트랩 참고 url
https://django-bootstrap4.readthedocs.io/en/latest/installation.html

create.html

{% load bootstrap4 %}
<div style="text-align: center; max-width: 500px; margin: 4rem auto">
        <div class="mb-4">
            <h4>SignUp</h4>
        </div>
        <form action="" method="post">
            {% csrf_token %}
<!--            {{ form }}-->
            {% bootstrap_form form %}
            <input type="submit" class="btn btn-dark rounded-pill col-6 mt-3">
        </form>

    </div>

head.html

@font-face {
            font-family: 'NanumSquareR';
            src: local('NanumSquareR'),
            url("{% static 'fonts/NanumSquareR.otf' %}") format("opentype");
       }

base.html

<body style="font-family: 'NanumSquareR'; ">

DetailView를 이용한 개인 페이지 구현

views.py

class AccountDetailView(DetailView):
    model = User
    context_object_name = 'target_user'
    template_name = 'accountapp/detail.html'

detail.html 생성

{% extends 'base.html' %}

{% block content %}

    <div>
        <div style="text-align: center; max-width: 500px; margin: 4rem auto;">
            <p>
                {{ target_user.data_joined }}
            </p>
            <h2 style="font-family: 'NanumSquareB' ">
                {{ target_user.username }}
            </h2>
        </div>
    </div>

{% endblock %}

urls.py에서 path 연결

path('detail/<int:pk>', AccountDetailView.as_view(), name='detail'),

int:pk란 특정 유저 객체에 부여된 고유한 키이다. pk라는 이름의 int 정보를 받겠다. 몇번 유저 정보에 접근할 것인지


UpdateView를 이용한 비밀번호 변경 구현

views.py

class AccountUpdateView(UpdateView):
    model = User
    form_class = AccountUpdateForm
    success_url = reverse_lazy('accountapp:hello_world')
    template_name = 'accountapp/update.html'

update.html 생성

{% extends 'base.html' %}
{% load bootstrap4 %}

{% block content %}

    <div style="text-align: center; max-width: 500px; margin: 4rem auto">
        <div class="mb-4">
            <h4>Change Info</h4>
        </div>
        <form action="{% url 'accountapp:update' % pk=user.pk}" method="post">
            {% csrf_token %}
<!--            {{ form }}-->
            {% bootstrap_form form %}
            <input type="submit" class="btn btn-dark rounded-pill col-6 mt-3">
        </form>

    </div>

{% endblock %}

urls.py

path('update/<int:pk>', AccountUpdateView.as_view(), name='update'),

아이디가 변경되는 것을 막기

CreateForm을 상속받아 아이디 변경 부분을 비활성화 한다.

class AccountUpdateForm(UserCreationForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.fields['username'].disabled = True

🤓 새로 알게된 점

django를 처음 배우는거라 이 파트들은 모든게 새롭다.
reverse와 reverse_lazy 차이점과 아이디가 변경되는 것을 막기위한 구문이 가장 기억에 남고 구문에 대한 것은 복습해야겠다.

profile
안녕하세요

0개의 댓글