2012-11-24 2 views
0

프로젝트에서 select 태그가 기본값 인 option에 있어야합니다. 변수를 특정 숫자로 설정하면 해당 옵션이 페이지가로드 될 때 선택됩니다. 어떤 이유로, 옵션이 변수와 동일한지를 알기 위해 사용하는 코드는 항상 false를 반환합니다.Django : 템플릿 언어 비교는 항상 false를 반환합니다.

View.py

@login_required 
def display_work(request, id, chapter = 1): 
    info = dict() 
    work = Work.objects.get(id = id) 
    chapters = Chapter.objects.filter(work = id).order_by("order_number") 
    info['title'] = work.title 
    info['summery'] = work.summery 
    info['current_chapter'] = chapter # the number the options are compared to 
    print chapter 
    info['id'] = id 
    num_chapters = 0 
    chapter_list = [] 
    for c in chapters: 
     temp = (c.title, c.order_number) # where the numbering for the options is set (see template code) 
     chapter_list.append(temp) 
     num_chapters += 1 
    info['total_chapter'] = num_chapters 
    content = chapters[int(chapter)-1].content 
    return render_to_response("SubMain/display_work.html", {'STATIC_URL':STATIC_URL, "info":info, "chapters": chapter_list, "content": content}) 

템플릿 : 템플릿은 옵션의 작성은 현재 챕터 있는지 점검 목록을 실행합니다. 그렇다면 "선택"해야합니다.

{% for t, o in chapters %} 
<option value="/work/{{ info.id }}/{{ o }}" {% if o == info.current_chapter %} selected="selected" {% endif %}>Chapter {{ o }}: {{ t }}</option> 
{% endfor %} 

그러나 코드를 실행할 때마다 아무것도 선택되지 않습니다 (if 태그에있는 내용 포함). 디버깅을 통해 나는 o이 2이고 info.current_chapter도 2임을 확인했습니다.

+0

당신은'O' 모두가 '동일한 유형 info.current_chapter'으로되어 있는지 있습니까? 두 가지 모두'int() '여야하지만, 그 중 하나는 문자열입니다 (대개 요청 변수에서 나온 문자열이기 때문에). –

+0

@MartijnPieters 그 생각은했지만, 둘 다 같은 유형이라고 생각합니다. 'info.curent_chapter'는 요청 변수가 아닙니다. (Wait, URL parameters count?),'o'는 모델의 정수 필드에서옵니다. –

+1

예, URL 매개 변수가 중요합니다. 타입을 다시 확인 ('repr()'을 사용하여'print 1'과'print '1'이 콘솔에서 똑같이 보이는지 확인하십시오). –

답변

1

템플릿에 '=='대신 '='연산을 사용해보십시오.

<option value="/work/{{ info.id }}/{{ o }}" {% if o = info.current_chapter %} selected="selected" {% endif %}>Chapter {{ o }}: {{ t }}</option> 
1

시도 ifequal

{% for t, o in chapters %} 
    <option value="/work/{{ info.id }}/{{ o }}" {% ifequal o info.current_chapter %} selected="selected" {% endifequal %}>Chapter {{ o }}: {{ t }}</option> 
    {% endfor %} 
관련 문제