Django CBV (1) - ํšŒ์›๊ฐ€์ž…

2021. 5. 23. 14:22ใ†Backend/๐Ÿ Python

FBV(function based view)๊ฐ€ ์•„๋‹Œ CBV(class based view)๋กœ ํšŒ์›๊ฐ€์ž…์„ ์ž‘์„ฑํ•˜๋ฉด,

Django๊ฐ€ ์ œ๊ณตํ•˜๋Š” class๋ฅผ ์ƒ์†๋ฐ›๊ธฐ ๋•Œ๋ฌธ์— ๋” ๊ฐ„๊ฒฐํ•œ ์ฝ”๋“œ๋กœ ์ž‘์„ฑํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

Views.py

from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django.views.generic import CreateView
from django.urls import reverse_lazy


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

์šฐ์„  views.py์—์„œ AccountCreateView๋ผ๋Š” ํด๋ž˜์Šค๋ฅผ ์ž‘์„ฑํ•ฉ๋‹ˆ๋‹ค.

๊ทธ๋ฆฌ๊ณ  ํ•ด๋‹น ํด๋ž˜์Šค๋Š” CreateView๋ผ๋Š” ํด๋ž˜์Šค๋ฅผ ์ƒ์†๋ฐ›๋Š”๋ฐ, ์ด๋Š” Django์—์„œ ๊ธฐ๋ณธ์œผ๋กœ ์ œ๊ณตํ•˜๋Š” ํด๋ž˜์Šค, ์ฆ‰ ์ด๋ฏธ ๊ตฌํ˜„๋˜์–ด ์žˆ๋Š” ์ฝ”๋“œ๋ฅผ ์ƒ์†ํ•จ์„ ๋œปํ•ฉ๋‹ˆ๋‹ค.

 

AccountCreateView๋Š” ๊ธฐ๋ณธ ๋ชจ๋ธ๋กœ User๋ฅผ ํ• ๋‹น๋ฐ›๋Š”๋ฐ, ์ด ์—ญ์‹œ Django์˜ ๊ธฐ๋ณธ ์ œ๊ณต ๋ชจ๋ธ์ž…๋‹ˆ๋‹ค. 

 

๋งˆ์ง€๋ง‰์œผ๋กœ UserCreationForm ์—ญ์‹œ Django ๊ธฐ๋ณธ ์ œ๊ณต ๋ชจ๋ธ์ž…๋‹ˆ๋‹ค.

ํšŒ์œˆ๊ฐ€์ž… form์„ html์—์„œ ์ผ์ผ์ด ๊ตฌํ˜„ํ•  ํ•„์š” ์—†์ด, ๋ฏธ๋ฆฌ ๊ตฌํ˜„๋œ form์„ ๊ฐ€์ ธ์™€ ๊ทธ๋Œ€๋กœ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋„๋ก ๋„์™€์ค๋‹ˆ๋‹ค.

 

 

์ด๋ ‡๊ฒŒ ํšŒ์›๊ฐ€์ž… form์˜ ๋‚ด์šฉ์„ ๋ชจ๋‘ ์ž‘์„ฑ ํ›„ ์ œ์ถœ ๋ฒ„ํŠผ์„ ๋ˆ„๋ฅด๋ฉด, 

success_url์— ํ• ๋‹น๋œ reverse_lazy์— ๋”ฐ๋ผ, urls.py์˜ hello_world๋ผ๋Š” ์ด๋ฆ„์˜ url๋กœ ๋ณด๋‚ด์ง‘๋‹ˆ๋‹ค.

(reverse_lazy์™€ reverse์˜ ์ฐจ์ด: ํ•จ์ˆ˜์™€ ํด๋ž˜์Šค๋ฅผ ๋ถˆ๋Ÿฌ์˜ค๋Š” ์ฐจ์ด ๋•Œ๋ฌธ์— cbv์—์„  reverse_lazy์‚ฌ์šฉ)

 

Urls.py

from django.urls import path
from account.views import AccountCreateView, hello_world

app_name = "account"

urlpatterns = [
    path('hello_world', hello_world, name='hello_world'),
    path('create/', AccountCreateView.as_view(), name='create'),  # class์—” as_view()๋ฅผ ๋ถ™์—ฌ์ฃผ์–ด์•ผ ํ•œ๋‹ค.
]

CBV์—์„  class ๋ช… ๋’ค์— .as_view()๋ฅผ ๋ถ™์—ฌ view์˜ ์—ญํ• ์„ ๋ถ€์—ฌํ•ฉ๋‹ˆ๋‹ค.

 

Create.html

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

 

 

bootstrap์„ ์ด์šฉํ•˜์—ฌ ์‹œ๊ฐ์ ์œผ๋กœ ๊พธ๋ฉฐ์ฃผ์—ˆ์Šต๋‹ˆ๋‹ค.