1. Django 준비 작업
- app등록
대상파일 : projects /mysite / config / setting.py
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
# Local App
"pybo.apps.PyboConfig",
]
- 관리자 모드에 Article 모듈 등록
대상파일 : projects /mysite / config / apps.py
from django.contrib import admin
from .models import Article
# Register your models here.
admin.site.register(Article)
- urls 설정
1) 전역 설정
대상파일 : projects / mysite / config / urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('pybo/', include('pybo.urls')),
]
2) app내 url 설정
대상파일 : projects / mysite / pybo / urls.py
from django.urls import path, include
from .views import HomePageView, AboutPageView, ArticleDetailView
app_name = 'pybo' # namespace 사용 -> 이후 pybo:name명 형식으로 별칭 명명
urlpatterns = [
path('', HomePageView.as_view(), name='home'),
path('about/', AboutPageView.as_view(), name='about'),
path('<int:pk>/', ArticleDetailView.as_view(), name='article_detail'),
]
- 모델 설정
대상파일 : projects / mysite / pybo / urls.py
from django.db import models
class Article(models.Model):
text = models.TextField()
def __str__(self):
return self.text[:50]
- Template폴더 생성 및 환경설정
폴더 생성 : projects / Templates / pybo
환경설정 : projects / config / setting.py
TEMPLATES = [
{
"DIRS": [
Path(BASE_DIR).joinpath('templates'),
], # 공통 templates 설정
- static폴더 생성 및 환경설정
폴더 생성 : projects / static
환경설정 : projects / config / setting.py
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/
STATIC_URL = "static/"
STATICFILES_DIRS = [
Path(BASE_DIR).joinpath('static'),
]
css파일 생성 :
projects / static / bootstrap.min.css
projects / static / bootstrap.min.js
template 파일에 css 적용
{% load static %}
<html>
<head>
<title>Django blog</title>
<link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:400" rel="stylesheet">
<link href="{% static 'base.css' %}" rel="stylesheet">
</head>
..... (생략)
2. view 설정
대상파일 : projects / mysite / pybo / views.py
2-1 HttpResponse를 이용한 출력 - template 불필요
from django.http import HttpResponse
def index(request):
return HttpResponse("안녕하세요 pybo에 오신것을 환영합니다.")
2-2 Html 파일을 이용한 출력 - render함수 이용
대상파일 : projects / mysite / pybo / views.py
from django.shortcuts import render
def index(request):
return render(request, 'pybo/hello.html')
출력 대상 : projects / Templates / pybo / hellow.html
<p> hello world!</p>
2-3 generic class view를 이용한 출력 - TemplateView이용
1) url 설정
대상파일 : projects / mysite / pybo / urls.py
as_view()함수를 이용
from django.urls import path, include
from .views import HomePageView, AboutPageView, ArticleDetailView
app_name = 'pybo' # namespace 사용 -> 이후 pybo:name명 형식으로 별칭 명명
urlpatterns = [
path('', HomePageView.as_view(), name='home'),
path('about/', AboutPageView.as_view(), name='about'),
path('<int:pk>/', ArticleDetailView.as_view(), name='article_detail'),
]
2) view 설정
대상파일 : projects / mysite / pybo / views.py
출력 대상 : projects / Templates / pybo / hellow.html
template_name을 이용하여 나타낼 html파일 지정
from django.views.generic import TemplateView
class HomePageView(TemplateView):
template_name = 'pybo/hello.html'
2-4 generic class view를이용한 출력 - ListView이용 - 모델 전체내역 리스트로 출력
1) models.py 모델생성
2) apps.py 모델 등록
3) urls.py 설정 - 2.3과 동일
4) view 설정 - ListView 이용
from django.views.generic import TemplateView, ListView
from .models import Article
class HomePageView(ListView):
model = Article
template_name = 'pybo/home.html'
# 명시적 리스트 이름 지정 ( listview 경우 )
# object_list(기본 이름) -> 'all_articles_list'(지정 이름)
context_object_name = 'all_articles_list'
5) list를 출력할 template파일 생성
- 대상 파일 : projects / Templates / pybo / base.html - base html
<header>
<a href="{% url 'pybo:home' %}">Home</a> |
<a href="{% url 'pybo:about' %}">About</a>
</header>
{% block content %}
{% endblock content %}
- 대상 파일 : projects / Templates / pybo / index.html - extended html
{% extends "pybo/base.html" %}
{% block content %}
<h1>Message board homepage</h1>
<ul>
<!-- object_list -> all_articles_list -->
{% for article in all_articles_list %}
<li>{{ article.text }}</li>
{% endfor %}
</ul>
{% endblock content %}
2-5 generic class view를 이용한 출력 - DetailView이용 - 모델 개별 상세 내역 출력
1) models.py 모델생성 - 위와 동일
2) apps.py 모델 등록 - 위와 동일
3) urls.py 설정 추가
path('<int:pk>/', ArticleDetailView.as_view(), name='article_detail'),
4) view 설정 - DetailView 이용
class ArticleDetailView(DetailView):
model = Article
template_name = 'pybo/article_detail.html'
# 명시적 리스트 이름 지정 ( detailview경우 )
# object, article (기본이름) -> 다른 이름 ( page )
# context_object_name = 'page'
5) 개별 객체 출력할 template파일 생성
- 대상 파일 : projects / Templates / pybo / base.html - base html
<header>
<a href="{% url 'pybo:home' %}">Home</a> |
<a href="{% url 'pybo:about' %}">About</a>
</header>
{% block content %}
{% endblock content %}
- 대상 파일 : projects / Templates / pybo / article_detail.html - extended html
{% extends "pybo/base.html" %}
{% block content %}
<div class="post-entry">
<h2>{{ object.title }}</h2> <!-- 자동생성된 article, object를 통한 개체 접근 가능-->
<!-- 다름 이름 지정을 위해 view 클래스정의에 context_object_name 에 이름 지정 -->
<p>{{ object.body }}</p>
</div>
{% endblock content %}
2-6 generic class view를 이용한 출력 - CreateView이용 - 개별 모델 생성
1) models.py 모델 get_absolute_url 함수 추가
def get_absolute_url(self):
# Reverse는 Django가 URL템플릿 이름(pybo:article_detail)으로 객체를 참조 <-- URLConf에서 확인 가능
# article/1 부터 주소 생성
return reverse('pybo:article_detail', args=[str(self.id)])
2) apps.py 모델 등록 - 위와 동일
3) urls.py 설정 추가
path('new/', ArticleCreateView.as_view(), name='article_new'),
4) view 설정 추가 - CreateView 이용
from django.views.generic.edit import CreateView
class ArticleCreateView(CreateView):
model = Article
template_name = 'pybo/article_new.html'
fields = ['title', 'author', 'body'] # template에 표사할 field
5) 개별 객체 출력할 template파일 수정 및 생성
- 대상 파일 : projects / Templates / pybo / base.html - base html
{% load static %}
<html>
<head>
<title>Django blog</title>
<link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:400" rel="stylesheet">
<link href="{% static 'base.css' %}" rel="stylesheet">
</head>
<body>
<header>
<div class="nav-left">
<h1><a href="{% url 'pybo:home' %}">Django blog</a></h1>
</div>
<div class="nav-right">
<a href="{% url 'pybo:article_new' %}">+ New Blog Post</a>
</div>
</header>
<div>
{% block content %}
{% endblock content %}
</div>
</body>
</html>
- 대상 파일 : projects / Templates / pybo / article_new.html - extended html
{% extends 'pybo/base.html' %}
{% block content %}
<h1>New Article</h1>
<form action="" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Save">
</form>
{% endblock content %}
2-7 generic class view를 이용한 출력 - UpdateView이용 - 개별 모델 편집
1) models.py 모델 get_absolute_url 함수 계
def get_absolute_url(self):
# Reverse는 Django가 URL템플릿 이름(pybo:article_detail)으로 객체를 참조 <-- URLConf에서 확인 가능
# article/1 부터 주소 생성
return reverse('pybo:article_detail', args=[str(self.id)])
2) apps.py 모델 등록 - 위와 동일
3) urls.py 설정 추가
path('<int:pk>/edit/', ArticleUpdateView.as_view(), name='article_edit'),
4) view 설정 추가 - UpdateView 이용
class ArticleUpdateView(UpdateView):
model = Article
template_name = 'pybo/article_edit.html'
fields = ['title', 'body'] # template에 표사할 field
5) 개별 객체 출력할 template파일 수정 및 생성
- 대상 파일 : projects / Templates / pybo / base.html - base html
2-6 과 동일
- 대상 파일 : projects / Templates / pybo / article_detail.html - 편집 링크 추가
{% extends 'pybo/base.html' %}
{% block content %}
<div class="post-entry">
<h2>{{ object.title }}</h2> <!-- 자동생성된 article, object를 통한 개체 접근 가능-->
<!-- 다름 이름 지정을 위해 view 클래스정의에 context_object_name 에 이름 지정 -->
<p>{{ object.body }}</p>
</div>
<p><a href="{% url 'pybo:article_edit' object.pk %}">+ Edit Blog Article</a></p>
{% endblock content %}
- 대상 파일 : projects / Templates / pybo / article_edit.html - extended html
{% extends 'pybo/base.html' %}
{% block content %}
<h1>Edit Article</h1>
<form action="" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Update">
</form>
{% endblock content %}
2-8 generic class view를 이용한 출력 - DeleteView이용 - 개별 모델 삭제
1) models.py 모델 get_absolute_url 함수 계승
def get_absolute_url(self):
# Reverse는 Django가 URL템플릿 이름(pybo:article_detail)으로 객체를 참조 <-- URLConf에서 확인 가능
# article/1 부터 주소 생성
return reverse('pybo:article_detail', args=[str(self.id)])
2) apps.py 모델 등록 - 위와 동일
3) urls.py 설정 추가
path('<int:pk>/delete/', ArticleDeleteView.as_view(), name='article_delete'),
4) view 설정 추가 - DeleteView 이용
class ArticleDeleteView(DeleteView):
model = Article
template_name = 'pybo/article_delete.html'
# reverse와 반대 개념 - view가 종료될때까지 article삭제 중지 대기
success_url = reverse_lazy('pybo:home')
5) 개별 객체 출력할 template파일 수정 및 생성
- 대상 파일 : projects / Templates / pybo / base.html - base html
2-6 과 동일
- 대상 파일 : projects / Templates / pybo / article_detail.html - 삭제 링크 추가
{% extends 'pybo/base.html' %}
{% block content %}
<div class="post-entry">
<h2>{{ object.title }}</h2> <!-- 자동생성된 article, object를 통한 개체 접근 가능-->
<!-- 다름 이름 지정을 위해 view 클래스정의에 context_object_name 에 이름 지정 -->
<p>{{ object.body }}</p>
</div>
<p><a href="{% url 'pybo:article_edit' object.pk %}">+ Edit Blog Article</a></p>
<p><a href="{% url 'pybo:article_delete' object.pk %}">+ Delete Blog Article</a></p>
{% endblock content %}
- 대상 파일 : projects / Templates / pybo / article_edit.html - extended html
{% extends 'pybo/base.html' %}
{% block content %}
<h1>Delete Article</h1>
<form action="" method="post">{% csrf_token %}
<p>Are you sure you want to delete "{{ object.title }}"?</p>
<input type="submit" value="Confirm">
</form>
{% endblock content %}
'장고' 카테고리의 다른 글
[ Django ] 기타 설정 (0) | 2023.05.03 |
---|---|
[ Django ] 내장 인증 (0) | 2023.05.03 |
[ Django ] Index (0) | 2023.05.02 |
App생성 (0) | 2023.04.12 |
댓글