django-crispy-forms / crispy-tailwind

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

How to add classes to all the widgets and labels #107

Closed ghost closed 5 months ago

ghost commented 2 years ago

Hi,

I have implemented dark mode on my site so for that, I need to add classes as such on every form field and label. dark:text-gray-100 dark:bh-gray-700

How can I achieve this?

amitjindal commented 2 years ago

@abhijeet-cn See this comment on how I did this. I am hoping this gets merged into the project and helps everyone.

https://github.com/django-crispy-forms/crispy-tailwind/issues/90#issuecomment-911907801

ghost commented 2 years ago

Thanks @amitjindal it's really a much-needed feature.

blasferna commented 2 years ago

@abhijeet-cn based on what i have seen you can add classes to widgets globally using CRISPY_CLASS_CONVERTERS in your settings.py. I don't know if it is supported by all widgets.

CRISPY_CLASS_CONVERTERS = {
    'textinput': 'dark:text-gray-100 dark:bh-gray-700'
}

A way to modify label classes is using FormHelper like this:

from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Field

class BookForm(forms.ModelForm):
    class Meta:
        model = Book
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper()
        # applying custom label class
        self.helper.label_class = "dark:text-gray-100 dark:bh-gray-700"
        self.layout = Layout(
            'name',
            'author',
            'publisher',
        )

Other way to use custom style is using CSSContainer, see #61

GitRon commented 5 months ago

Since the user creating this issues has been deleted, I'll close this ticket.