问题
I am using Django's Form Wizard package to create a 4-step form. I have created forms for each of the four steps. It's working fine. In my case I have created 4 separate templates and each step of the form wizard uses its own template.
But each of these templates that I have created is substantially the same. Below is the code that is in each one. I cut and pasted this from elsewhere. It works, but I don't fully understand how or why:
<form action="" method="post">{% csrf_token %}
<table>
{{ wizard.management_form }}
{% if wizard.form.forms %}
{{ wizard.form.management_form }}
X
{% for form in wizard.form.forms %}
{{ form }}
{% endfor %}
{% else %}
Y
{{ wizard.form }}
{% endif %}
</table>
{% if wizard.steps.prev %}
<button name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">{% trans "Previous Step" %}</button>
{% endif %}
<input type="submit" value="{% trans "Next Step" %}"/>
</form>
What I need to do is alter the layout for the form in step #2 of 4. I don't want the form's input elements to be stacked on top of each other as they currently are. I want do something a little different by manipulating the the .
But I don't know how to do this. Can someone show me a template in which they are using the actual named form elements instead of just {{wizard.form}}? Keep in mind, if there is a validation error, I still need that to show up on this webpage. How to accomplish all that? A simple example of what your template looks like would be ideal.
回答1:
If you want to control the rendering of your forms you should render the form fields manually. Your forms are still standard Django forms after all.
But each of these templates that I have created is substantially the same.
You certainly shouldn't repeat the same template for each step.
It would be cleaner to use your template as a base template instead and extend this base template in the templates you provide for the steps where you want to customize the layout. That way you could even easily embed extra CSS or JS for certain steps.
So instead of
{% for form in wizard.form.forms %}
{{ form }}
{% endfor %}
you would create the following block in your base template
{% block form %}
{{ wizard.form }}
{% endblock %}
That way you can customize the rendering of your forms for certain steps by simply overriding the form block.
{% extends "base_step.html" %}
{% block form %}
{{ wizard.form.example_field_to_show }}
...
{% endblock %}
来源:https://stackoverflow.com/questions/14670531/how-to-change-the-layout-for-templates-in-a-django-form-wizard