Django2 (4. Class-based View란?) feat.페스트캠퍼스

min seung moon·2021년 3월 15일
0

Django

목록 보기
20/37

1. Class-based View란?

  • 이전 강의에서는 def 함수로 사용
  • class로 사용하면 상속이라는 개념으로 재사용성이나 활용성이 좋다

01. 예시

# models.py
from django.db import models

class Publisher(models.Model):
    name = models.CharField(max_length=30)
    address = models.CharField(max_length=50)
    city = models.CharField(max_length=60)
    state_province = models.CharField(max_length=30)
    country = models.CharField(max_length=50)
    website = models.URLField()

    class Meta:
        ordering = ["-name"]

    def __str__(self):
        return self.name

class Author(models.Model):
    salutation = models.CharField(max_length=10)
    name = models.CharField(max_length=200)
    email = models.EmailField()
    headshot = models.ImageField(upload_to='author_headshots')

    def __str__(self):
        return self.name

class Book(models.Model):
    title = models.CharField(max_length=100)
    authors = models.ManyToManyField('Author')
    publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE)
    publication_date = models.DateField()
from django.views.generic import ListView
from books.models import Publisher

class PublisherList(ListView):
    model = Publisher
from django.urls import path
from books.views import PublisherList

urlpatterns = [
    path('publishers/', PublisherList.as_view()),
]
That’s all the Python code we need to write. We still need to write a template, however. We could explicitly tell the view which template to use by adding a template_name attribute to the view, but in the absence of an explicit template Django will infer one from the object’s name. In this case, the inferred template will be "books/publisher_list.html" – the “books” part comes from the name of the app that defines the model, while the “publisher” bit is the lowercased version of the model’s name.

https://docs.djangoproject.com/en/3.1/topics/class-based-views/generic-display/

profile
아직까지는 코린이!

0개의 댓글

관련 채용 정보