2021-08-14
Model <-> View <-> Controller
django : Model <-> Template <-> View
django의 처리과정
https://docs.djangoproject.com/en/3.2/
https://www.djangoproject.com/
https://wikidocs.net/book/4223
python.org/downloads
code.visualstudio.com/Download
jetbrains.com/ko-kr/pycharm/download
github.com/saintdragon2/do_it_django_a_to_z
https://getbootstrap.com/docs/4.6/getting-started/download/
django-admin startproject do_it_django_prj .
python .\manage.py runserver
http://127.0.0.1:8000/
make migrate
python manage.py migrate
python manage.py createsuperuser
python .\manage.py runserver
http://127.0.0.1:8000/admin
python .\manage.py startapp firstapp
#views.py
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):
return HttpResponse('<h1>Hello First App</h1>')
#urls.py
import firstapp.views
from firstapp import views
urlpatterns = [
path('admin/', admin.site.urls),
path('firstapp/', views.index)
]
python .\manage.py startapp blog
python .\manage.py startapp single_pages
settings.py
settings.py : 장고 프로젝트의 설정 정보 저장
urls.py : 사용자가 어떤 URL로 접근했을 때 어떤
웹 사이트를 동작시킬 지 정리해놓은 파일
INSTALLED_APPS
python .\manage.py makemigrations
Migration이란? – 데이터베이스에 적용시켜야 하는 변화에 대한 기록
python manage.py migrate
from .models import Post
admin.site.register(Post)
python .\manage.py runserver
TIME_ZONE = 'Asia/Seoul'
USE_TZ = False
from django.db import models
# Create your models here.
class Post(models.Model):
title = models.CharField(max_length=30)
content = models.TextField()
created_at = models.DateTimeField(auto_now=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return f'[{self.pk}]{self.title}'
python .\manage.py makemigrations
python .\manage.py migrate
python .\manage.py runserver
2021-08-15
함수기반 -->
표지판 역할의 urls.py
사용자가 접근했을 때 어떤 페이지로 들어가야하는지를 알려주는 역할
do_it_django_prj\urls.py
from django.contrib import admin
from django.urls import path
import firstapp.views
from firstapp import views
urlpatterns = [
path('admin/', admin.site.urls),
path('firstapp/', views.index)
]
->
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('firstapp/', include('firstapp.urls'))
]
firstapp\urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index),
]
python .\manage.py runserver
urlpatterns = [
path('admin/', admin.site.urls),
path('firstapp/', include('firstapp.urls')),
path('blog/', include('blog.urls')),
]
blog\urls.py
from django.urls import path, include
from . import views
urlpatterns = [
path('', views.index),
]
blog\view.py
from django.shortcuts import render
# Create your views here.
def index(request):
return render(request, 'index.html')
DJango 템플릿 언어
http://pythonstudy.xyz/python/article/307-Django-%ED%85%9C%ED%94%8C%EB%A6%BF-Template
Django 템플릿에서 사용하는 특별한 태크 및 문법을 Django 템플릿 언어 (Django Template Language)라 부른다. 템플릿 언어는 크게 템플릿 변수, 템플릿 태크, 템플릿 필터, 코멘트 등으로 나눌 수 있다.
django shell
python .\manage.py shell
>>> from blog.models import Post
>>> Post.objects.all()
>>> Post.objects.get(id=1)
>>> Post.objects.get(pk=1)
>>> Post.objects.last()
>>> p=Post.objects.get(id=1)
>>> p.created_at
blog\views.py
from django.shortcuts import render
from .models import Post
# Create your views here.
def index(request):
posts = Post.objects.all()
return render(request, 'blog/index.html', { 'posts' : posts })
templates\blog\index.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>blog</title>
</head>
<body>
<h1>Blog</h1>
{% for p in posts %}
<h3>{{ p }}</h3>
{% endfor %}
</body>
</html>
>>> exit()
python .\manage.py runserver
http://127.0.0.1:8000/blog/
<h1>Blog</h1>
{% for p in posts %}
<hr/>
<h2>{{ p.title }}</h2>
<h4>{{p.created_at }}</h4>
<h4>{{ p.content }}</h4>
{% endfor %}
def index(request):
posts = Post.objects.all().order_by('-pk')
return render(request, 'blog/index.html', { 'posts' : posts })
urlpatterns = [
path('<int:pk>/', views.single_post_page),
path('', views.index),
]
def single_post_page(request, pk):
post = Post.objects.get(pk=pk)
return render(request, 'blog/single_post_page.html', { 'post': post, } )
blog/single_post_page.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>{{ post.title }} - Blog</title>
</head>
<body>
<nav>
<a href="/blog/">Blog</a>
</nav>
<h1>{{ post.title }}</h1>
<h4>{{ post.created_at }}</h4>
<p>{{ post.content }}</p>
<hr/>
<h3>필요시 댓글 구현</h3>
</body>
http://127.0.0.1:8000/blog/1/
<h2><a href="{{ p.get_absolute_url }}">{{ p.title }}</a></h2>
http://127.0.0.1:8000/blog/
class Post(models.Model):
title = models.CharField(max_length=30)
content = models.TextField()
created_at = models.DateTimeField(auto_now=True)
updated_at = models.DateTimeField(auto_now=True)
def get_absolute_url(self):
return f'/blog/{self.pk}'
def __str__(self):
return f'[{self.pk}]{self.title}'
path('', include('single_pages.urls')),
from django.urls import path
from . import views
urlpatterns = [
path('about_me', views.about_me),
path('', views.landing),
]
def landing(request):
return render(request, 'single_pages/landing.html')
def about_me(request):
return render(request, 'single_pages/about_me.html')
http://127.0.0.1:8000/about_me
http://127.0.0.1:8000/
클래스기반 -->
https://docs.djangoproject.com/en/3.2/
class-based views
https://docs.djangoproject.com/en/3.2/topics/class-based-views/
blog/views.py
from django.views.generic import ListView
class PostList(ListView): # index() 삭제
model = Post
blog/urls.py
urlpatterns = [
path('<int:pk>/', views.single_post_page),
#path('', views.index),
path('', views.PostList.as_view()),
]
index.html -> post_list.html
blog\urls.py
from django.urls import path, include
from . import views
urlpatterns = [
path('<int:pk>/', views.PostDetail.as_view()),
path('', views.PostList.as_view()),
blog\views.py
from .models import Post
from django.views.generic import ListView, DetailView
class PostList(ListView): # index() 삭제
model = Post
ordering = '-pk'
def single_post_page(request, pk):
return render()
class PostDetail(DetailView): # single_post_page() 삭제
model = Post
post_list.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>blog</title>
</head>
<body>
<nav>
<a href="/">Home</a>
<a href="/blog/">Blog</a>
<a href="/about_me">About Me</a>
</nav>
Blog
{% for p in post_list %}
<hr/>
<h2>{{ p.title }}</h2>
<h2><a href="{{ p.get_absolute_url }}">{{ p.title }}</a></h2>
<h4>{{p.created_at }}</h4>
<h4>{{ p.content }}</h4>
{% endfor %}
</body>
</html>
http://127.0.0.1:8000/blog/
blog_list.html 파일의 내용을 post_list.html 파일로 덮어 쓰기한 후 서버 다시 실행
http://127.0.0.1:8000/blog/
settings.py
STATIC_URL = '/static/'
<!DOCTYPE html>
{% load static %}
<html>
<head>
<title>Blog</title>
<meta charset="UTF-8">
<link href="{% static 'blog/bootstrap/bootstrap.min.css' %}" rel="stylesheet" media="screen" type="text/css">
</head>
python .\manage.py migrate
python .\manage.py runserver
http://127.0.0.1:8000/blog/
post_list.html
{% for p in post_list %}
<!-- Blog post-->
<div class="card mb-4">
<img class="card-img-top" src="https://via.placeholder.com/750x300" alt="Card image cap" />
<div class="card-body">
<h2 class="card-title"> {{ p.title }} </h2>
<p class="card-text"> {{ p.content }} </p>
<a class="btn btn-primary" href="{{ p.get_absolute_url }}">Read More →</a>
</div>
<div class="card-footer text-muted">
Posted on {{ p.created_at }} by
<a href="#!">작성자</a>
</div>
</div>
{% endfor %}
http://127.0.0.1:8000/blog/
C:\Users\512-17\Downloads\Django\다운로드\startbootstrap-blog-post-18e5cfdfb75bc7b06fbb8b04b7d957e0395fe8cc\startbootstrap-blog-post-18e5cfdfb75bc7b06fbb8b04b7d957e0395fe8cc
post_detail.html
C:\Users\512-17\PycharmProjects\do_it_django_a_to_z\blog\static\blog\css\blog
<link href="{% static 'blog/css/blog-post.css' %}" rel="stylesheet" media="screen">
Pillow 라이브러리 설치하고 마이그레이션
settings.py
import os
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, '_media')
models.py
class Post(models.Model):
title = models.CharField(max_length=30)
content = models.TextField()
head_image = models.ImageField(upload_to='blog/images/%Y/%m/%d/', blank=True)
created_at = models.DateTimeField(auto_now=True)
updated_at = models.DateTimeField(auto_now=True)
python manage.py makemigrations
python manage.py migrate
python .\manage.py runserver
http://127.0.0.1:8000/admin/login/?next=/admin/
do_it_django_prj/urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
blog/templates/blog/post_list.html
<img class="card-img-top" src="{{ p.head_image.url }}" alt="Card image cap" />
blog/templates/blog/post_detail.html
<img class="img-fluid rounded" src="{{ post.head_image.url }}"" alt="">
C:\Users\512-17\PycharmProjects\do_it_django_a_to_z\venv\lib\site-packages\django\db\models\fields\files.py, line 40, in _require_file
{% if p.head_image %}
<img class="card-img-top" src="{{ p.head_image.url }}" alt="{{ p }} head_image" />
{% else %}
<img class="card-img-top" src="https://picsum.photos/id/{{ p.id }}/200/100" alt="random_image" />
{% endif %}
<!-- Preview Image -->
{% if post.head_image %}
<img class="img-fluid rounded" src="{{ post.head_image.url }}" alt="{{ post.title }} head_image">
{% else %}
<img class="card-img-top" src="https://picsum.photos/id/{{ post.id }}/200/100" alt="random_image" />
{% endif %}
<p class="card-text"> {{ p.content | truncatewords:10 }} </p>
'푸닥거리' 카테고리의 다른 글
URL Encoding 시 특수문자코드 (0) | 2021.12.03 |
---|---|
웹 개발을 위한 JSP_Sevlet 기본 (0) | 2021.10.09 |
mac m1 Big Sur ld: library not found for -lSystem (0) | 2021.02.27 |
chrome 사용자 백업하기 (0) | 2020.12.26 |
영문 아웃룩에서 한글 아웃룩으로 변경 (0) | 2020.12.26 |
댓글