Django Template

  • setting.py : APP_DIRS: True๋กœ ์„ค์ •ํ•˜๊ธฐ.

  • ๋งŒ๋“  App ์•ˆ์— App์ด๋ฆ„/templates/app์ด๋ฆ„์˜ ํด๋” ์ƒ์„ฑ

    App์ด๋ฆ„/emplate/App์ด๋ฆ„ ๋ผ๊ณ  ๋งŒ๋“ค ํ•„์š” ์—†์ด, ๊ทธ๋ƒฅ App์ด๋ฆ„/templates์— ๋„ฃ์–ด๋„ ๋˜์ง€ ์•Š์„๊นŒ? ๋งŒ์•ฝ ๋™์ผํ•œ template ์ด๋ฆ„์ด ๋‹ค๋ฅธ ์–ดํ”Œ๋ฆฌ์ผ€์ด์…˜์— ์žˆ์„ ๊ฒฝ์šฐ Django ๋Š” ์ด ๋‘˜๊ฐ„์˜ ์ฐจ์ด๋ฅผ ๊ตฌ๋ถ„ํ•˜์ง€ ๋ชปํ•ฉ๋‹ˆ๋‹ค.

404 Error

๊ธฐ์กด ๋ฐฉ์‹.

try:
        question = Question.objects.get(pk=question_id)
    except Question.DoesNotExist:
        raise Http404("Question does not exist")
    return render(request, 'polls/detail.html', {'question': question})

์กฐ๊ธˆ ๋” ํŽธํ•œ ๋ฐฉ๋ฒ•.

from django.shortcuts import get_object_or_404, render
 
from .models import Question
# ...
def detail(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    # get_list_or_404() : list Check
    return render(request, 'polls/detail.html', {'question': question})

Template ์—์„œ ํ•˜๋“œ์ฝ”๋”ฉ๋œ URL ์„ ์ œ๊ฑฐํ•˜๊ธฐ

URL์ด ๋ณ€๊ฒฝ๋˜๋ฉด URL์„ ํฌํ•จํ•œ ์ฝ”๋“œ๋ฅผ ์ „๋ถ€ ๋ณ€๊ฒฝํ•ด์•ผํ•˜๋Š” ๋ฌธ์ œ์ ์„ ํ•ด๊ฒฐํ•˜๊ธฐ ์œ„ํ•ด ์ œ๊ฑฐํ•œ๋‹ค.

๊ฐ•๊ฒฐํ•ฉ ์ฝ”๋“œ

html

<li><a href="/memos/{{ memo.id }}/">{{ memo.content }}</a></li>

์•ฝ๊ฒฐํ•ฉ ์ฝ”๋“œ

    (r'^memos/(?P<memo_id>[0-9]+)/$', views.detail, name='detail')

html

URL ๊ตฌ์—ญ๋‚˜๋ˆ„๊ธฐ

๋‹ค๋ฅธ App์˜ URLS.py๋ฅผ ์‚ฌ์šฉํ•˜๊ธฐ ์œ„ํ•ด

app_name = 'memos' # App ์ด๋ฆ„ ์„ ์–ธ

html

Reference