Django CBV (3) - DetailView

2021. 5. 23. 15:40ใ†๐Ÿ Python/Django CBV

views.py

from django.contrib.auth.models import User
from django.views.generic import DetailView

class AccountDetailView(DetailView):
    model = User
    context_object_name = 'target_user'  # target์ด ๋˜๋Š” user์˜ ์ •๋ณด๋ฅผ ๋ณด์ผ ์ˆ˜ ์žˆ๋„๋ก
    template_name = "detail.html"

User์˜ detailํ•œ ์ •๋ณด๋ฅผ ๋ณด๊ณ  ์‹ถ์„ ๋• DetailView class๋ฅผ ์ƒ์† ๋ฐ›์Šต๋‹ˆ๋‹ค. 

 

model ์€ ์—ญ์‹œ ๋ฏธ๋ฆฌ ์ •์˜๋œ User ๋ชจ๋ธ์„ ๊ฐ€์ ธ์˜ต๋‹ˆ๋‹ค.

 

context_object_name = 'target_user'๋„ ์ง€์ •ํ•ด์ค์‹œ๋‹ค .

์ด๋ ‡๊ฒŒ target_user๋ฅผ ํ• ๋‹นํ•˜์ง€ ์•Š์œผ๋ฉด,

๋‹ค๋ฅธ ์‚ฌ๋žŒ์˜ detail page ์— ๋“ค์–ด๊ฐ€๋„, ์ž์‹ ์˜ detail ์ •๋ณด๋งŒ ๋ณด์—ฌ์ง€๊ฒŒ ๋ฉ๋‹ˆ๋‹ค.

์ด๋Š” ์šฐ๋ฆฌ์˜ ์ง€ํ–ฅ์ ์ด ์•„๋‹ˆ๊ธฐ์—, context_object_name์„ ๊ผญ ํ• ๋‹นํ•ด์ฃผ๋„๋ก ํ•ฉ์‹œ๋‹ค.

 

*context_object_name์€ DetailView() ํด๋ž˜์Šค๊ฐ€ ์ƒ์†๋ฐ›๋Š”, SingleObjectMixin ํด๋ž˜์Šค ๋‚ด๋ถ€์— ์ •์˜๋œ ํ•„๋“œ์ž…๋‹ˆ๋‹ค. 

 

template_name ์€ AccountDetailView ๊ฐ€ ๋ Œ๋”๋ง ๋  template ์„ ์ •์˜ํ•ฉ๋‹ˆ๋‹ค.

์ €๋Š” detail.html ์„ ๋”ฐ๋กœ ๋งŒ๋“ค์—ˆ์Šต๋‹ˆ๋‹ค.

 

urls.py

from django.contrib.auth.views import LogoutView, LoginView
from django.urls import path

from account.views import AccountCreateView, hello_world, AccountDetailView

app_name = "account"

urlpatterns = [
    path('hello_world', hello_world, name='hello_world'),
    path('login/', LoginView.as_view(template_name='login.html'), name="login"),
    path('logout/', LogoutView.as_view(), name='logout'),
    path('create/', AccountCreateView.as_view(), name='create'),  # class์—” as_view()๋ฅผ ๋ถ™์—ฌ์ฃผ์–ด์•ผ ํ•œ๋‹ค.
    path('detail/<int:pk>', AccountDetailView.as_view(), name='detail'),
]

target_user๋ฅผ ์ง€์ •ํ•˜์˜€๊ธฐ์—, ํ•ด๋‹น target_user์— ๋งž๋Š” pk๋ฅผ url์— ๋งคํ•‘ํ•ด์ฃผ์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.

 

detail.html

    <div>
        <div style="text-align: center; max-width: 500px; margin: 4rem auto;">
            <p>

                {{ target_user.date_joined }}
            </p>
            <h2>
                {{ target_user.username }}
            </h2>
        </div>
    </div>

 

AccountDetailView ์—์„œ ์ •์˜ํ•œ template_name ๋Œ€๋กœ detail.html์— target_user์˜ detail ์ •๋ณด๋ฅผ ํ™•์ธํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. 

๋ฌผ๋ก  ์ด๋Š” ์œ ์ €์˜ detail ์ •๋ณด์ด๊ธฐ์—, ํšŒ์›๊ฐ€์ž…๊ณผ ๋กœ๊ทธ์ธ ๊ณผ์ •์„ ๊ฑฐ์นœ ํ›„์— ํ™•์ธ ๊ฐ€๋Šฅํ•œ ์ •๋ณด์ž…๋‹ˆ๋‹ค. 

 

 

ChangeInfo ์™€ Quit ์€ ๋‹ค์Œ ํฌ์ŠคํŒ…์—์„œ UpdateView์™€ DeleteView ์—์„œ ๋‹ค๋ค„๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.

'๐Ÿ Python > Django CBV' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

Django CBV (2) - ๋กœ๊ทธ์ธ, ๋กœ๊ทธ์•„์›ƒ ๊ตฌํ˜„  (0) 2021.05.23
Django CBV (1) - ํšŒ์›๊ฐ€์ž…  (0) 2021.05.23
Django Bootstrap4 ์—ฐ๋™  (0) 2021.05.23