ChoiceField的过滤模板-Django



在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 %}

我想要的是拥有其他两个不同的模板,其中有任何区别,并根据Choice Field上的选择加载它们,我想通过添加某种有条件的条件,可以看出一种方法并加载其他模板(HTML文件)。

有什么想法?

可以将{% 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选择的值有效。

最新更新