我不确定这是一个好习惯,但如果你真的希望它在同一个 html 文件中:
使用 Django 模板语言来评估用户想要的“视图”。
修改您的 html 文件以将其包含在正文中。
首先我们制作一个表单,询问用户他想要什么视图,然后我们使用上下文字典中的数据进行评估
<form role="form" id="view_form" method="post" action="<same url>">
<input type="radio" name="view" value="view1" checked> View #1 <br> <!-- this one will be checked by default -->
<input type="radio" name="view" value="view2"> View #2 <br>
<input type="radio" name="view" value="view3"> View #3 <br>
<button type="submit" name="submit">Change View</button>
</form>
{% if view == view1 %}
<!-- your code here -->
{% elif view == view2 %}
<!-- your code here -->
{% endif %}
在views.py 中修改您的视图以捕获表单中的数据并将其添加到上下文字典中。
def page(request):
context_dict = {}
if request.method=='POST':
view = request.POST.get['view']
context_dict['view'] = str(view)
#The rest of your code here
....
但我认为最好在视图函数中评估视图值并为每个值呈现不同的模板
def page(request):
# Your code first
view_value = None
if request.method=='POST':
view = request.POST.get['view']
if view = 'view1':
render(request, 'your_template.html', context_dict) # If you don't have a context, simply don't include it in this line
elif view = 'view2':
render(request, 'your_template2.html', context_dict)
... # All your other possible views
else:
render(request, 'default_template.html', context_dict) # If there's no match, load the default one.