240401 django

송용진·2024년 4월 1일

하드코딩된 url 대신

<a href = "/polls/1/">Poll Detail</a>

url 이름을 사용하는 방법

<a href = "{ url 'poll_detail' 1 %}">Poll Detail </a>
{% extends "base_generic.html" %}

{% block title %}{{ section.title }}{% endblock %}

{% block content %}
<h1>{{ section.title }}</h1>

{% for story in story_list %}
<h2>
  <a href="{{ story.get_absolute_url }}">
    {{ story.headline|upper  }}
  </a>
</h2>
<p> {{ story.tease|truncatewords:"100" }} </p>
{% endfor %}
{% endblock %}

default

{{ value | default : "nothing" }}

length

{{ value|length }}

filesizeformat

{{ value | filesizeformat }}

for

<ul>
{% for athlete in athlete_list %}
  <li>{{ athlete.name }}</li>
{% endfor %}
</ul>

if, elif, else

{% if athlete_list %}
	운동선수 수 : {{ athlete_list|length }}
{% elif athlete_in_locker_room_list %}
	운동선수들이 곧 탈의실에서 나올 것 입니다!
{% else %}
	운동선수 없음.
{% endif %}

if 태그에서 필터와 다양한 연산자 사용

{% if athlete_list|length > 1 %}
	팀 : {% for athlete in athlete_list %}
{% endfor %}
{% else %}
	운동선수 : {{ athlete_list.0.name }}
{% endif %}

0은 athlete_list 변수에서 첫 번째 요소

F 함수 사용 예시

def vote(request, question_id):
	question = get_object_or_404(Question, pk = question_id)
	try:
		selected_choice = question.choice_set.get(pk = request.POST["choice"])
	except (KeyError, Choice.DoesNotExist):
    	# Redisplay the question voting form.
        return render(
        	request,
            "polls/detail.html",
            {
            	"question": question,
                "error_message": "You didnt't select a choice.",
            },
        )
     else:
     	selected_choice.votes = F("votes") + 1
        selected_choice.save()
        # Always return an HttpResponseRedirect after successfully dealing
        # with POST data. This prevents data from being posted twice 
        # if a user hits the Back button.
        return HttpResponseRedirect(reverse("polls:results",args=(question.id,)))

get_object_or_404
이 함수는 주어진 모델과 일치하는 객체를 검색하고,
해당 객체가 존재하지 않을 경우 404 페이지를 반환
즉, 해당 객체를 찾을 수 없을 때
뷰에서 HTTP 404 Not Found 오류를 발생시킴

F 함수 동작 예시

profile
개발자

0개의 댓글