19. 요약정리

1. Django 공부 방향과 원리

Django는 Python으로 빠르게 웹을 개발하기 위해 나온 Web Framework입니다. 대부분의 기능들이 자동화 되어 있으며 공식문서도 잘 되어 있어 공식문서 정독을 한번 하면 다른 문서는 필요 없을 정도로 상세 내용을 가지고 있습니다.
우리는 지금까지 간단한 카페 블로그를 만들어 보았습니다. 그러나 Django에 극히 일부분만을 다룬 것입니다. 더 강력한 Django의 기능을 사용하고 싶으시다면 AskDjango의 강의를 참고하시길 권해드립니다. 또한, 책은 아래 3권을 추천해드려요.
  1. Python 웹 프로그래밍(초급, 공식문서에 가까운 상세한 설명)
  1. Django로 쉽게 배우는 배프의 오지랖 파이썬 웹 프로그래밍(실전 응용)
  1. AWS 클라우드 기반의 Django 웹 어플리케이션(실전 응용)
 
아래는 Django의 기능을 전체 도식화 정리 해놓은 것입니다. 보시면서 놓치신 것이 없으신지 체크해보시기 바랍니다.
 
notion imagenotion image

2. URL 설계

💡
전체 소스코드는 https://github.com/paullabkorea/jejucodingcamp 에서 보실 수 있습니다. 프로젝트 실행을 해보고 싶으시다면 해당 사이트의 README 설명서를 따라 소스코드를 다운로드 받고 세팅해주세요.
 
챕터에서 수정한 순서대로 빨간색 네모를 그려보았습니다. 처음에는 urls.py에서 url 파싱을 하였습니다. 아래 코드는 우리가 수정한 코드 전문입니다.
notion imagenotion image
 
urls.py
from django.contrib import admin from django.urls import path from main.views import index, about, write, cafelist, cafedetails from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('', index, name='index'), path('about/', about, name='about'), path('write/', write, name='write'), path('cafelist/', cafelist, name='cafelist'), path('cafelist/<int:pk>/', cafedetails, name='cafedetails'), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
 
settings.py
# (생략) INSTALLED_APPS = [ 'main', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] # (생략) STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / 'staticfiles' MEDIA_ROOT = BASE_DIR / 'media' MEDIA_URL = '/media/'

3. VIEW 로직 설계

URL 설계가 끝났다면 URL에서 연결해준 각종 함수를 views에서 만들어 줍니다.
 
notion imagenotion image
 
views.py
from django.shortcuts import render, redirect from .models import Cafe def index(request): context = { 'locations' : Cafe.locations } return render(request, 'main/index.html', context) def about(request): return render(request, 'main/about.html') def cafelist(request): selected_locations = request.GET.getlist('locations') search = request.GET.get('search') if selected_locations: cafes = Cafe.objects.filter(location__in=selected_locations) elif search: cafes = Cafe.objects.filter(name__icontains=search) else: cafes = Cafe.objects.all() context = { 'cafes': cafes } return render(request, 'main/cafelist.html', context) def cafedetails(request, pk): cafe = Cafe.objects.get(pk=pk) context = { 'cafe': cafe, } return render(request, 'main/cafedetails.html', context) def write(request): if request.method == 'POST': data = { 'name': request.POST.get('name'), 'location': request.POST.get('location'), 'phone': request.POST.get('phone'), 'insta': request.POST.get('insta'), 'content': request.POST.get('content'), 'mainphoto': request.FILES.get('mainphoto'), 'subphoto': request.FILES.get('subphoto'), } cafe = Cafe.objects.create(**data) return redirect(f'/cafelist/{cafe.pk}/') context = { 'locations': Cafe.locations, } return render(request, 'main/write.html', context)
 

4. MODEL 데이터베이스 설계

아래 코드는 후에 작성하였지만 설계를 제대로 하셨다면 세 번째에서 작업할 사항입니다. 각종 게시물 등 필요한 model을 설계합니다.
전부 작성한 후에는 makemigrations와 migrate로 DB에 반영합니다.
 
notion imagenotion image
models.py
from django.db import models class Cafe(models.Model): name = models.CharField(max_length=50) locations = [ ('Hangyeong-myeon', '한경면'), ('Hallim-eup', '한림읍'), ('Aewol-eup', '애월읍'), ('Jeju-si', '제주시'), ('Jocheon-eup', '조천읍'), ('Gujwa-eup', '구좌읍'), ('Daejeong-eup', '대정읍'), ('Andeok-myeon', '안덕면'), ('Seogwipo-si', '서귀포시'), ('Namwon-eup', '남원읍'), ('Pyoseon-myeon', '표선면'), ('Seongsan-eup', '성산읍'), ('Udo-myeon', '우도면'), ] location = models.CharField(max_length=50, choices=locations) lat = models.FloatField(null=True) lng = models.FloatField(null=True) mainphoto = models.ImageField(blank=True, null=True) subphoto = models.ImageField(blank=True, null=True) published_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) content = models.TextField() phone = models.CharField(max_length=20, null=True) insta = models.CharField(max_length=20, null=True) def __str__(self): return self.name
from django.contrib import admin from .models import Cafe admin.site.register(Cafe)

5. Templates

이번에는 Template을 작성 해보겠습니다. 중간에 모델 설계를 하지 않았다면 3번째 작업할 사항입니다. 우리는 templates라는 폴더 아래 main이라는 폴더를 만들어서 그 안에 각종 템플릿을 작성하였습니다.
 
notion imagenotion image