gpt4 book ai didi

django - 如何重用 Django 模板?

转载 作者:行者123 更新时间:2023-11-28 04:16:37 25 4
gpt4 key购买 nike

目前,我有几乎两个完全相同的模板,它们使用相同的 Django 表单,但是这两个表单中只有 1 个参数发生变化,即 action 方法,即,

Django 形式

class DropDownMenu(forms.Form):
week = forms.ChoiceField(choices=[(x,x) for x in range(1,53)]
year = forms.ChoiceField(choices=[(x,x) for x in range(2015,2030)]

模板 1

<form id="search_dates" method="POST" action="/tickets_per_day/">
<div class="row">
<div style="display:inline-block">
<h6>Select year</h6>
<select name="select_year">
<option value={{form.year}}></option>
</select>
</div>
<button type="submit">Search</button>
</div>
</form>

模板 2

<form id="search_dates" method="POST" action="/quantitative_analysis/">
<div class="row">
<div style="display:inline-block">
<h6>Select year</h6>
<select name="select_year">
<option value={{form.year}}></option>
</select>
</div>
<button type="submit">Search</button>
</div>
</form>

唯一不同的是操作方法,所以我想知道是否可以重复使用一个仅在操作方法中有所不同的模板。如果可能的话,你能帮我写代码吗?

我检查了这个问题django - how to reuse a template for nearly identical models?但我没有在我的模板中使用任何模型。

最佳答案

当然有办法。 {% include %}来救援!

为您的表单创建一个基本模板,如下所示:

<!-- form_template.html -->

<form id="search_dates" method="POST" action="{{ action }}">
<div class="row">
<div style="display:inline-block">
<h6>Select year</h6>
<select name="select_year">
<option value={{form.year}}></option>
</select>
</div>
<button type="submit">Search</button>
</div>
</form>

注意占位符 action。我们将在下一步中需要它。

现在,您可以重用此模板,只需编写:

<!-- a_template.html -->

{% include 'form_template.html' with action='/tickets_per_day/' %}


<!-- b_template.html -->

{% include 'form_template.html' with action='/quantitative_analysis/' %}

关于django - 如何重用 Django 模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45925157/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com