考虑一下Django上的这个模型:
class My_model(models.Model):
my_choices = { '1:first' 2:second'}
myfield1=CharField()
myfield2=CharField(choices=my_choices)然后在我的表格上:
class My_form(forms.ModelForm):
class Meta:
model = My_model
fields = ['myfield1', 'myfield2']我的观点是:
def get_name(request):
if request.method == 'POST':
form = My_form(request.POST)
if form.is_valid():
return HttpResponseRedirect('/')
else:
form = My_form()
return render(request, 'form/myform.html', {'form': form})在我的模板上:
{% extends "base.html" %}
{% block content %}
<form action="/tlevels/" method="POST">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit">
</form>
{% endblock %}在我的base.html上,我将像这样加载这个模板:
{% extends "base.html" %}
{% block content %}
{% load crispy_forms_tags %}
<div class="p-3 mb-2 bg-info text-white" style="margin-left:20px; margin-bottom:20px;">Status</div>
<div class="form-row" style="margin-left:20px; margin-bottom:20px; margin-top:20px;">
<div class="form-group col-md-6 mb-0">
{{ form.myfield1|as_crispy_field }}
</div>
<div class="form-group col-md-6 mb-0">
{{ form.myfield2|as_crispy_field }}
</div>
</div>
<input type="submit" class="btn btn-primary" value="Submit" style="margin-left:20px;">
</form>
{% endblock %}我想要的是,有另外两个不同的模板,无论它们有什么不同,加载它们取决于在ChoiceField上所做的选择,我猜一种方式可以是在视图上,通过添加某种条件,并加载一个不同的模板(html文件)。
有什么想法吗?
发布于 2019-03-03 07:03:38
可以将{% include %}与变量一起使用。
def some_view_after_post(request):
# ... lookup value of myfield2 ...
return render(request, "path/to/after_post.html", {'myfield2: myfield2})在after_post.html模板中:
<!-- include a template based on user's choice -->
<div class="user-choice">
{% include myfield2 %}
</div>您需要确保用户不可能注入错误的选择。例如,在将myfield2 choice添加到上下文之前,请确保它的值有效。
https://stackoverflow.com/questions/54963241
复制相似问题