easy way to get crispy forms to work with django-filter
Asked Answered
O

2

11

specifically, using the example template in the django-filter docs:

{% extends "base.html" %}

{% block content %}
<form action="" method="get">
    {{ filter.form.as_p }}
    <input type="submit" />
</form>
{% for obj in filter %}
    {{ obj.name }} - ${{ obj.price }}<br />
{% endfor %}
{% endblock %}

Do others know how to get crispy forms to work?

Inserting the following makes the form render nicely, but I can't get it to actually be functional.

{% crispy filter.form %}

figured it out - was too easy. I swear I tried this method several times earlier, although I must have been doing something wrong. Sorry to ask such a simple question.

Answer is to change:

{{ filter.form.as_p }}

To:

{{ filter.form|crispy }}
Osborne answered 26/2, 2014 at 15:36 Comment(0)
L
5

I just needed to add the load crispy tags.

{% extends "base.html" %}
{% load crispy_forms_tags %}

{% block content %}
    <form action="" method="get">
        {{ filter.form|crispy }}
        <input type="submit" />
    </form>
    {% for obj in filter %}
        {{ obj.name }} - ${{ obj.price }}<br />
    {% endfor %}
{% endblock %}
Loony answered 19/6, 2014 at 13:26 Comment(1)
{% crispy filter.form %} also works FWIW. Did you figure out a way to use Crispy Form's helper.layout = Layout(...) to define the submit button, field widgets, etc from the Python side?Batholith
M
0

If you want to also override the layout of the django-filter's filter form, you can override the form property on FilterSet class, attach the helper to it and return it.

class ValuationFilters(django_filters.FilterSet):
    class Meta:
        model = Valuation
        fields = (
            '...',
        )

    @property
    def form(self):
        form = super().form

        form.helper = FormHelper()
        form.helper.layout = Layout(
            Fieldset(
                'First arg is the legend of the fieldset',
                '...',
            ),
            Submit('submit', 'Submit', css_class='button is-primary'),
        )

        return form

Make sure to also use the special cripsy tag instead of |crispy template filter for the helper to actually get executed.

{% load crispy_forms_tags %}

<form method="get">
    {% crispy filter.form %}
</form>

This is in response to Addison Klinke's question on hum3's answer.

Marilynnmarimba answered 21/3 at 20:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.