애플리케이션 생성 명령어
C:\dev\workspace\django1\ch5Lab>python manage.py startapp books
mysite/settings.py 파일에 books 애프리케이션 등록
#[ch5Lab/mysite/settings.py]
...(생략)...
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'polls.apps.PollsConfig', # 추가
'books.apps.BooksConfig', # 추가
]
..(생략)...
# [ch5Lab/books/models.py]
from django.db import models
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()
def __str__(self):
return self.title
class Author(models.Model):
name = models.CharField(max_length=50)
salutation = models.CharField(max_length=100)
email = models.EmailField()
def __str__(self):
return self.name
class Publisher(models.Model):
name = models.CharField(max_length=50)
address = models.CharField(max_length=100)
website = models.URLField()
def __str__(self):
return self.name
# [ch5Lab/books/admin.py]
from django.contrib import admin
from books.models import Book, Author, Publisher
admin.site.register(Book)
admin.site.register(Author)
admin.site.register(Publisher)
D:\dev\workspace\django1\ch5Lab>python manage.py makemigrations
D:\dev\workspace\django1\ch5Lab>python manage.py migrate
# [ch5Lab/mysite/urls.py]
from django.contrib import admin
from django.urls import path, include
from mysite import views # 추가
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.HomeView.as_view(), name='home'), # 추가
path('polls/', include('polls.urls')),
path('books/', include('books.urls')),
]
# [ch5Lab/books/urls.py]
from django.urls import path
from . import views
app_name = 'books'
urlpatterns = [
# /books/
path('', views.BooksModelView.as_view(), name='index'),
# /books/book/
path('book/', views.BookList.as_view(), name='book_list'),
# /books/author/
path('author/', views.AuthorList.as_view(), name='author_list'),
# /books/publisher/
path('publisher/', views.PublisherList.as_view(), name='publisher_list'),
# /books/book/99/
path('book/<int:pk>/', views.BookDetail.as_view(), name='book_detail'),
# /books/author/99/
path('author/<int:pk>/', views.AuthorDetail.as_view(), name='author_detail'),
# /books/publisher/99/
path('publisher/<int:pk>/', views.PublisherDetail.as_view(), name='publisher_detail'),
]
# [ch5Lab/books/views.py]
from django.views.generic.base import TemplateView
from django.views.generic import ListView
from django.views.generic import DetailView
from books.models import Book, Author, Publisher
#--- TemplateView
# 특별한 로직이 없고 템플릿 파일을 랜더링하는 경우 TemplateView 제네릭 뷰를 상속받아 사용하면 간단하다
class BooksModelView(TemplateView):
template_name = 'books/index.html'
def get_context_data(self, **kwargs):
# get_context_data() 메소드를 정의할 때는 반드시 첫 줄에 super() 메소드를 호출해야 한다.
context = super().get_context_data(**kwargs)
# books 애플리케이션의 첫 화면에 테이블 리스트를 보여주기 위해 컨텍스트 변수model_list에 담아서 템플릿 시스템에 넘겨주고 있다.
context['model_list'] = ['Book', 'Author', 'Publisher']
return context
#--- ListView
# Book 테이블로부터 모든 레코드를 가져와 object_list라는 컨텍스트 변수를 구성한다.
# 템플렛 파일은 디폴트로 books/book_list.html 파일이 된다.
class BookList(ListView):
model = Book
class AuthorList(ListView):
model = Author
class PublisherList(ListView):
model = Publisher
#--- DetailView
class BookDetail(DetailView):
model = Book
class AuthorDetail(DetailView):
model = Author
class PublisherDetail(DetailView):
model = Publisher
github참고...생략
# [ch5Lab/templates/base.html]
<!DOCTYPE html>
<html lang="en">
<head>
{% load static %}
<link rel="stylesheet" href="{% static 'admin/css/base.css' %}" />
<title>{% block title %}My Amazing Site{% endblock %}</title>
</head>
<body>
<div id="sidebar">
{% block sidebar %}
<ul>
<li><a href="/">Project_Home</a></li>
<li><a href="/admin/">Admin</a></li>
</ul>
{% endblock %}
<br>
</div>
<div id="content">
{% block content %}{% endblock %}
</div>
</body>
</html>
# [ch5Lab/mysite/urls.py]
from django.contrib import admin
from django.urls import path, include
from mysite import views # 추가
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.HomeView.as_view(), name='home'), # 추가
path('polls/', include('polls.urls')),
path('books/', include('books.urls')),
]
[ch5Lab/mysite/views.py]
from django import apps
from django.views.generic.base import TemplateView
from django.apps import apps # 추가
#--- TemplateView
class HomeView(TemplateView):
template_name = 'home.html'
# get_context_data() 메소드를 정의할 때는 반드시 첫 줄에 super() 메소드를 호출해야 한다.
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
# mysite 프로젝트 하위에 있는 애플리케이션들의 리스트를 보여주기 위해 컨텍스트 변수 app_list에 담아서 템플릿 시스템에 넘겨준다.
context['app_list'] = ['polls', 'books']
return context
{% extends "base.html" %}
{% block content %}
<h2>shkim Django Applications</h2>
<ul>
# 뷰로부터 app_list 컨텍스트 변수를 전달받아서 app_list에 들어있는 애플리케이션명(appname)들을 하나씩 순회하면서 화면에 보여준다.
{% for appname in app_list %}
# add 템플릿 필터를 사용하여 애플리케이션명에 필요한 문자열을 붙여주고 있다. 예)애플리케이션명이 'books'라면 urlvar는 'books:index'가 된다.
{% with appname|add:":"|add:"index" as urlvar %}
<li><a href="{% url urlvar %}">{{ appname }}</a></li>
{% endwith %}
{% endfor %}
</ul>
{% endblock content %}
함수형 뷰와 클래스형 뷰의 장단점 공부필요 클래스형이 재사용에 좋다는데... 둘 차이점 확실하게 알아두기
실습중인 adminLTE의 polls페이지가 함수형을 되어있는데 연습 겸 클래스형으로 바꾸기 도전해볼기