Class Based View in Django

Docs

Class Based View

  • View ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“ค์–ด์ฃผ๋Š” class

  • function-based-view ์™€ ๋น„๊ตํ–ˆ์„ ๋•Œ ์ฐจ์ด์  & ์žฅ์ ์ด ์žˆ๋‹ค!

    • GET, POST ์š”์ฒญ๊ณผ ๊ฐ™์€ HTTP method๋ฅผ ์กฐ๊ฑด ๋ถ„๊ธฐ๊ฐ€ ์•„๋‹Œ ๊ฐ๊ฐ์˜ method๋กœ ํ‘œํ˜„ ํ•  ์ˆ˜ ์žˆ๋‹ค

      HTTP method ๊ฐ€ class method ์™€ 1:1 ๋Œ€์‘์ด๋ผ ๊ฐ€๋…์„ฑ์ด ์ข‹๋‹ค

  • ํ™•์žฅ์„ฑ์ด ๋›ฐ์–ด๋‚จ

    • Mixin ๋ชจ๋“ˆ์„ ํ™œ์šฉํ•˜์—ฌ ํ™•์žฅ์„ฑ์„ ๊ทน๋Œ€ํ™” ํ•  ์ˆ˜ ์žˆ๋‹ค

      • Mixin: class์— ๋ถ€๊ฐ€์ ์ธ ๊ธฐ๋Šฅ์ด๋‚˜ ์ •๋ณด๋ฅผ ์ถ”๊ฐ€ํ•ด์ฃผ๊ธฐ ์œ„ํ•œ ๋ชจ๋“ˆ

  • ๋กœ์ง์ด ๋ณต์žกํ•ด๋„ ์ฝ”๋“œ์˜ ์ง๊ด€์„ฑ์„ ์œ ์ง€ ํ•  ์ˆ˜ ์žˆ์Œ

Function generic view vs class based generic view

Function generic view

ex)

def index(request):
    articles = Article.objects.all()
    return render(request, 'articles/index.html', {'articles': articles})

class based generic view

ex)

views.py

from django.views.generic import ListView, DetailView

class ArticleListView(ListView):
    model = Article
    # template_name = 'articles/๋ชจ๋ธ๋ช…_list.html' -> ์ด๋ ‡๊ฒŒ ํ•˜๋ฉด ์ž๋™์œผ๋กœ ์ฐพ์Œ
    # context_object_name = 'object_list'

class ArticleDetailView(DetailView):
    model = Article

urls.py

from django.contrib import admin
from django.urls import path
from articles import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('articles/', views.ArticleListView.as_view()),
    path('articles/<int:pk>',views.ArticleDetailView.as_view()),
]

+

Django REST API Auth

https://django-rest-auth.readthedocs.io/en/latest/installation.html

Last updated