Django模板:如何在模板中使用模型中的字段?

时间:2010-01-20 18:06:03

标签: django django-templates

在此模板中,

<body><p>You searched for: <strong>{{ first }} {{ last }}</strong></p>

{% if lawyers %}
    <p>There are {{ lawyers|length }} schoolmates of <strong>{{ first }} {{ last }}</strong> in the database:</p>
    <ul>
        {% for lawyer in lawyers %}
        <li> {{ lawyer.first }} {{ lawyer.last }} {{ lawyer.firm_name }} {{ lawyer.school }} {{ lawyer.year_graduated }}</li>
        {% endfor %}
    </ul>

{% else %}
    <p><strong>{{ first }} {{ last }}</strong> has no classmates in the database. Try another lawyer.</p>
{% endif %} 

我从搜索表单中选择了{{ first }}{{ last }},但没有选择其他参数,例如year_graduated

但我希望能够说:

<p>You searched for: <strong> {{ first }} {{ last }}, class of {{ year_graduated }} </strong> </p>

即使模板中没有lawyer.year_graduated,我如何才能使用{{1}}?

有关视图功能,请参阅my previous question

谢谢。

2 个答案:

答案 0 :(得分:2)

嗯,简单的方法就是将year_graduated添加到上下文字典中。

return render_to_response('search_results.html', {'lawyers': lawyers1, 'last': last_name, 'first': first_name, 'year_graduated': q_year[0], 'form': form})

答案 1 :(得分:0)

整个视图可以使用一些工作来使事情变得更容易。以下是一些快速更改(包括在另一个问题中讨论的更改):

def search_form(request):
    if request.method == 'POST':
        search_form = SearchForm(request.POST)
        if search_form.is_valid():
            last_name = search_form.cleaned_data['last_name']
            first_name = search_form.cleaned_data['first_name']
            fields = {}
            if last_name:
                lawyers = fields['last__iexact'] = last_name
            if first_name:
                lawyers = fields['first__icontains'] = first_name
            try:
                searched_lawyer = Lawyer.objects.get(**fields)
            except Lawyer.DoesNotExist:
                form = SearchForm()
                return render_to_response('not_in_database.html', {'last': last_name, 'first': first_name, 'form': form})
            except Lawyer.MultipleObjectsReturned:
                form = SearchForm(initial={'last_name': last_name})
                # Note: this breaks the current multiple returns functionality, up to you...
                return render_to_response('more_than_1_match.html', {'last': last_name, 'first': first_name, 'form': form}) 
            q_school = searched_lawyer.school
            q_year = searched_lawyer.year_graduated
            classmates = Lawyer.objects.filter(school__iexact=q_school).filter(year_graduated__icontains=q_year).exclude(last__icontains=last_name)
            form = SearchForm()
            return render_to_response('search_results.html', {'classmates': classmates, 'searched_lawyer': searched_lawyer, 'form': form})
    else:
        form = SearchForm()
        return render_to_response('search_form.html', {'form': form, })

所以现在不是在模板中使用“first”和“last”,而是使用“searching_lawyer.first”等等。(但这意味着您可以访问该律师的所有属性)模板)