python-django training (2)

남순식·2023년 12월 20일

01. Django Template

python-django (1) 이어쓰기

1-1. template

  • 먼저 python django에서 응답해줄 데이터를 렌더링할 html문서 template을 MyProjcet/templates에 만들고 config/setting.py에서
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates'],
        'APP_DIRS': True,
(... 생략 ...)

처럼
DIRS : [BASE_DIR / 'templets'] 해당 경로를 추가해주면

# 경로 : myapp/view.py

from django.shortcuts import render
from .models import MyClass

def index(request):
	my_class_list = MyClass.Objcets.order_by('-id')
	context = {'myClass_list': my_class_list}
	return render(request, 'myclass/myclass_list', context)

과 같이 데이터를 template에 렌더링할 수 있다.

또한 template에서는 {{ python객체 }} 와 같은 문법이나 {% for.. %} 이나 {% if ... %} 같은 python문법이 사용 가능하다.

  • 예제
def index(request):
	tmp_list = ['이것은', '임의의', '리스트입니다.']
	return render(request, 'myapp/index.html', {'tmp_list': tmp_list}
<body>
	{% for s in tmp_list %}
	<p> 순서: {{ forloob.counter }} </p> <!-- 1, 2, 3 -->
	<p> {{ s }} <p> <!-- 이것은, 임의의, 리스트입니다. -->
	{% forend %}
<body>
  • 반드시 forend, ifend까지 작성해주어야 한다.

1-1-1. 제네릭 뷰

  • Django 제네릭뷰를 사용해보진 않아서 간략하게 설명하고 넘어간다.

    • IndexView()
      • request url http://'domain' or 'IP'/ 에 렌더링 될 데이터를 정의하기만 하면 IndexView가 index 함수를 대체할 수 있다.
      • template을 명시하지 않으면 모델명_list.html을 template 이름으로 사용한다.
    • DetailView()
      • detail request url http://'domain' or 'IP'/{모델id} 에 렌더링 될 모델만 지정해주면 deatail함수를 대체할 수 있다.
      • template을 명시하지 않으면 모델명_detail.html을 template 이름으로 사용한다.
  • 이렇듯 모델의 목록 조회나 상세 조회는 제네릭뷰를 사용하는것이 매우 간편함을 알 수 있다. 단, 제네릭 뷰를 사용할 경우에는 복잡한 케이스에서 더 어렵게 작성되는 경우가 종종 있으니 주의하여 사용해야 함

1-2. URL 별칭, 네임스페이스

1-2-1. 별칭

  • request를 받기위해 endpoint를 정의해야한다. 하지만 모든 url을 Myproject/config/setting.py에서 관리하는 것은 매우 좋지 않은 방법이다.

  • app/urls.py에서

from django.urls import path

from . import views

urlpatterns = [
	path('', views.index, name='index')
	path('<int:my_model_id>', views.detail, name='detail')    
]

이렇게하면
index url = http://localhost:8000/myapp/
detail url = http://localhost:8000/myapp/{my_model_id}
처럼 별칭을 부여한 것이다.

1-2-2. 네임스페이스

  • 하나의 프로젝트에서 app이 여러개라면..
    • user_app, order_app.. 등 각 도메인이 하나의 앱으로 만들어 졌다면 url을 사용하기 위해 네임스페이스를 이용해야한다.

각각의 app/urls.py 에서

from django.urls import path

from . import views

app_name = 'myapp'

urlpatterns = [
	path('', views.index, name='index')
	path('<int:my_model_id>', views.detail, name='detail')    
]

과 같이 app_name을 추가해주면

  • template에서 {% url 'myapp:index' tmp_list %}처럼 사용할 수 있다.
  • redirect()에서도 사용할 수 있다.

02. form

  • url path에 있는 데이터는 myclass property에 매핑된다
  • request body같은 경우는 request.POST.get('property')로 받을 수 있다.
profile
응집력있는 시간을 보내기 위한 블로그

0개의 댓글