cssdjangotailwind-cssdaisyui

Django : Tailwind styling not applied to template variables with widget attributes


I'm trying to apply daisyUI styling in my django web-app project, and I'm note sure to understand what's happening with the styling : in my case, I try to add some daisyUI styling to an input text field generated dynamically by a django form :

#forms.py

class ProductForm(forms.ModelForm):
    class Meta:
        model = Product
        fields = '__all__'
        widgets = {
            'title': forms.TextInput(attrs={'class': 'form-control input input-primary w-full max-w-xs', 'placeholder':'Title'}),
            'description': forms.Textarea(attrs={'class': 'textarea textarea-primary w-full'})
        }
...

regarding this daisyUI docs page, I should have a rounded bordered input field (same idea with textarea).

Adding {{form.title}} inside a form tag in my template, Here is what it looks like : what I get vs. what I want.

The styling seems to be overridden somewhere but I'm unable to determine where that comes from...

I got the screenshot of "what I want" using my lines of code with this tailwind-play tool

More informations that could be useful :

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: ["../**/templates/**/*.html"],
  theme: {
    extend: {},
  },
  daisyui: {
    themes: ['light', 'dark'],
  },
  plugins: [require("@tailwindcss/typography"), require("daisyui")],
}

When looking for some similar issues (like this one) their styling problems seem to have their origin in the use of tailwind form plugin. But in my case I'm not using it..!

Any idea where this problem may come from ?

(I hope my explanations were clear enough as I don't have a developer background and my "most used" programming language is python so far)

Thank you in advance for your kind answers and your help 🙏


Solution

  • For dynamic classes that are generated by Django templates at runtime you have to whitelist those in Tailwind. Tailwind strips out all classes that are not present in the templates during the build process. They do this to reduce the size of the final css file.

    See how this applies to the messages framework and Tailwind alerts: https://django.wtf/blog/django-alerts-with-tailwind-and-daisyui/

    Modify tailwind.config.js to whitelist your css classes:

    module.exports = {
      content: [
        '../templates/**/*.html',
      ],
      theme: {},
      plugins: [
        require('@tailwindcss/forms'),
        require('@tailwindcss/typography'),
        require('@tailwindcss/line-clamp'),
        require('@tailwindcss/aspect-ratio'),
        require('daisyui'),
      ],
      daisyui: {},
      safelist: [
        'alert-info',
        'alert-success',
        'alert-warning',
        'alert-error',
      ],
    }