django-crispy-forms / crispy-tailwind

A Tailwind template pack for django-crispy-forms
MIT License
331 stars 56 forks source link

checkbox before label #100

Closed finevine closed 3 years ago

finevine commented 3 years ago

Hello, How can I implement a checkbox for a BooleanField before its label. For example :

For now, I have the label and then the checkbox input on a new line. I have got : Remember me

Thank you

finevine commented 3 years ago

I've found a way using this template in a crispy_form Field in the Layout:

{% load crispy_forms_field %}

<div class="mb-3" id="div_{{ field.auto_id }}">
    {% crispy_field field 'class' 'form-check-input' %}
    <label for="{{ field.id_for_label }}" class="text-gray-700 text-sm mb-2 {% if field.field.required %} requiredField{% endif %}">
        {{ field.label|safe }}{% if field.field.required %}<span class="asteriskField">*</span>{% endif %}
    </label>
</div>

EDIT : this template is missing a value. See my new comment below.

MaziyarMK commented 7 months ago

For future me:

class LoginForm(BaseLoginForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.helper = FormHelper()
        self.helper.layout = Layout(
            Field("login", "password"),
            Field("remember", template="partials/boolean_field.html"),
        )
LaundroMat commented 2 months ago

Is there a way to override a template in /tailwind/layout to have all checkboxes rendered with a custom template? I could change /tailwind/field.html and check for a checkbox input but I'd rather not touch that.

finevine commented 1 month ago

I do this (but have not manage to bulk change all) :

have a custom checkbox (with crispy_form a folder in templates

class Checkbox(forms.CheckboxInput):
    template_name = 'crispy_form/tailwind/checkbox.html'

then use it in a form

class AForm(forms.Form):
    a_field = forms.BooleanField(required=False, widget=Checkbox)

and the template (with a value !) :

<div class="mb-3" id="div_{{ field.auto_id }}">
    <input type="checkbox" 
           name="{% if field %}{{ field.name }}{% else %}{{ widget.name }}{% endif %}" 
           value="True" 
           id="{% if field %}{{ field.auto_id }}{% else %}{{ widget.attrs.id }}{% endif %}"
           class="form-checkbox h-5 w-5 text-gray-600"
           {% if field.value or option.attrs.selected %} checked {% endif %}>
    <label for="{{ field.auto_id }}" class="text-gray-700 mb-2 {% if field.field.required %} requiredField{% endif %}">
        {{ field.label|safe }}{% if field.field.required %}<span class="asteriskField">*</span>{% endif %}
    </label>
    {% if field.help_text %}
        <div class="text-sm text-gray-500 mt-1">{{ field.help_text }}</div>
    {% endif %}
</div>