[Django]-Django Crispy forms: moving buttons to top

3đź‘Ť

âś…

Django Crispy Forms doesn’t seem to support what you want to do from its API.
However, you can simply add the button markup yourself in the template where you render your form, you’ll only need to prevent crispy from rendering the form tag:

# form python code
def __init__(self, *args, **kwargs):
    super(MyForm, self).__init__(*args, **kwargs)
    self.helper.form_tag = False


{# template code #}
<form action="." method="POST">
  <input type="submit" value="Respond" name="respond">
  <input type="submit" value="Respond and Close" name="respond_and_close">
  <input type="submit" value="Close" name="close">
  <input type="submit" value="Change Owner" name="change_owner">     
  {% crispy form form.helper %}
</form>

Another possibility is overriding crispy’s whole_uni_form.html template. If you’re using the bootstrap template pack (default) you can create that file within a subdirectory called “bootstrap” inside your project’s template dir, and have it look like this:

{# templates/bootstrap/whole_uni_form.html #}
{% load crispy_forms_utils %}

{% specialspaceless %}
{% if form_tag %}<form {{ flat_attrs|safe }} method="{{ form_method }}" {% if form.is_multipart %} enctype="multipart/form-data"{% endif %}>{% endif %}
{% if form_method|lower == 'post' and not disable_csrf %}
    {% csrf_token %}
{% endif %}

{% if inputs %}
    <div class="form-actions">
        {% for input in inputs %}
            {% include "bootstrap/layout/baseinput.html" %}
        {% endfor %}
    </div>
{% endif %}

{% include "bootstrap/display_form.html" %}

{% if form_tag %}</form>{% endif %}
{% endspecialspaceless %}

Keep in mind that this will affect any form rendered using crispy in your site.

👤Gonzalo

Leave a comment