The issue arises when applying Tailwind styling to template variables that have widget attributes in Django

Currently, I am attempting to implement daisyUI styling in my django web application project, however, I am facing some confusion regarding the styling. The specific issue arises when I try to apply daisyUI styling to a dynamically generated input text field through 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'})
        }
...

According to this daisyUI documentation page, I should have a rounded bordered input field (similar concept with the textarea).

After inserting {{form.title}} within a form tag in my template, This is the discrepancy between what I currently have and the desired result.

The styling appears to be overridden from somewhere but pinpointing the source has been challenging...

I managed to replicate the "desired result" image by utilizing my code with this tailwind-play tool

Here are additional details that might be helpful:

  • I have locally installed django-browser-reload on my machine.
  • My tailwind.config.js file has the following structure :
/** @type {import('tailwindcss').Config} */
module.exports = {
  content: ["../**/templates/**/*.html"],
  theme: {
    extend: {},
  },
  daisyui: {
    themes: ['light', 'dark'],
  },
  plugins: [require("@tailwindcss/typography"), require("daisyui")],
}

  • I attempted to rerun npm run tailwind-watch, refresh the webpage using cmd+shift+R, and restart 'python manage.py runserver` each time I made modifications to verify if the styling would be correctly applied

  • I also experimented by incorporating this pre-made django project (which is a commendable effort!) and experiencing the same styling problem after adding a form to edit the template.

While researching similar issues (such as this one), it seems like their styling issues stem from the usage of tailwind form plugin. However, in my case, I am not using it..!

Any insights on where this issue may originate from?

(I hope my explanations were sufficiently clear, considering my non-developer background and limited experience beyond Python programming language)

Thank you in advance for any guidance and assistance provided 🙏

Answer №1

To ensure dynamic classes generated by Django templates are included in Tailwind, they need to be whitelisted. During the build process, Tailwind removes any classes not present in the templates to decrease the final css file size.

Learn how this is relevant to the messages framework and Tailwind alerts:

Edit tailwind.config.js to include your custom 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',
  ],
}

Answer №2

After conducting some tests, I discovered that the issue arises from a situation where when Django is running, the customized class attributes linked to my form fields (which are supposed to be tailwind styling classes) are not included in the final output css file generated when executing npm tailwind-watch.

It seems that because these specific class attributes are dynamically rendered by Django, they aren't being "watched" by the tailwind compiler, resulting in the respective styles not being saved in the output css file.

However, all of these explanations may seem a bit confusing as I am not entirely familiar with all the concepts involved and I am simply sharing my understanding. If anyone with a better grasp on this issue has encountered it before, please feel free to contribute by providing some insights through answers or comments. 🙏✌️

In conclusion, here is the workaround I implemented to ensure that my styling gets added to the tailwind css output:

I inserted a hidden <div> element with the same attribute classes directly within the widget elements in the template.

<div class="hidden form-control input input-primary w-full max-w-xs"></div>

I will update the title of my original question to provide clarity since my issue is unrelated to DaisyUI.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adjust the checkbox dimensions within the cells of a bootstrap table

I am utilizing bootstrap-table along with a column containing checkboxes. I need to adjust the size of the checkboxes in my code to be 25x25 pixels. However, when I try using the height and width CSS attributes, it does not seem to take effect. html < ...

What is typically regarded as the optimal size for a full-screen background image?

What is the ideal image size for a full-screen background? I currently have an image that is 1920x1080 pixels, but I'm unsure if that's suitable for desktop screens. Can you provide guidance on this? ...

I'm puzzled as to why my bootstrap dropdown menu is expanding to fill the entire width of the webpage despite its supposed small size

I recently created a drop-down menu and an input form using the code below: <div class="container-fluid"> <div class="dropdown"> <button class="btn btn-info dropdown-toggle" type="button&quo ...

How can I center a button instead of using "margin-left: 0" when its location changes on a smaller screen?

Website: When viewing the website on my desktop, the text over the top image - "Buckinghamshire Food Partnership believe that everyone is entitled to a Right to Food" and the button - "Get involved" are aligned to the left with a 10% margin. However, on a ...

Target the select element with a specific style applied, but restrict it to only be selected when nested within a div that shares the same style

Not quite sure about the effectiveness of the title, but here's what I'm attempting to accomplish. <div class="mystyle"> <select name="somename" id="somename"> <option value="Value1"> <option value="Value2" ...

Refreshing the page to dynamically alter background and text hues

I'm currently dealing with a website that generates a random background color for a div every time it is refreshed. I have a code that successfully accomplishes this: var colorList = ['#FFFFFF', '#000000', '#298ACC', &ap ...

Numerous animated elements within A-frame

Is there a way to incorporate animation into an A-Frame glTF model, causing it to smoothly move 5 spaces to the left and then 5 spaces forward? Below is my current code: <a-gltf-model color="#FFFFFF" width="1" height="1" de ...

Guide to updating the button's color when clicked

I need to change the color of an iconic button when it is clicked. The default color is the primary color, but when the button is clicked, it should change to red. This functionality is working correctly. After clicking the button, two hidden buttons shoul ...

Interconnected HTML div values impacting one another

Forgive me for the not-so-great title, as I am unsure of what this particular HTML coding method is called. That's why I am asking this question in the first place. I've written some code and I need to know what type of coding practice this is. ...

Looking to downgrade Django version specifically on MacOS

Currently, I am running Django version-3.1.5, but for my university course, they recommend testing with version-2.2.17. I'm curious about how to downgrade using MacOS Terminal. Whenever I try pip3 install Django-2.2.17, I receive an error stating that ...

What is the best way to use jQuery to update the color of an SVG shape?

Hello everyone! I'm excited to be a part of this community and looking forward to contributing in the future. But first, I could really use some assistance with what seems like a simple task! My focus has always been on web design, particularly HTML ...

Uncovering the source of glitchy Angular Animations - could it be caused by CSS, code, or ng-directives? Plus, a bonus XKCD comic for some light-hearted humor

Just finished creating an XKCD app for a MEAN stack class I'm enrolled in, and I'm almost done with it. However, there's this annoying visual bug that's bothering me, especially with the angular animations. Here is the link to my deploy ...

Smoothly reveal a border at the moment of transition

I currently have images set up as checkboxes that display a yellow border upon clicking with a transition effect. However, the transition of the border causes the images to shake and shutter slightly due to margin adjustments. To resolve this issue, I tri ...

Struggling to insert a high-quality image into inline divs of exactly 33.3333% width

After creating 3 inline divs, each taking up 33.333% of their parent width, I encountered an issue while trying to insert images into them. Whenever the image exceeds the 33.333% width of the div, it overflows outside the container. My goal is to make the ...

Looking for a solution to split barcode data across two text fields

I am looking to enhance my data input process by utilizing a barcode scanner in conjunction with JQuery. The barcode scanner I have reads both the serial number and model name of each product, but currently displays them together in one text field. Is ther ...

Exploring the distinction between absolute elements nested within other absolute elements and relative elements nested within absolute elements

My latest CSS experiment involved creating a flag of a country. Check out my code: div.flag { width: 900px; height: 600px; background-color: red; position: relative; } div.flag > div { position: absolut ...

I'm confused as to why only one of my HTML pages is accepting my CSS styling - not sure what's going on

I am facing an issue where the CSS styles are only being applied to one of the HTML pages I created. Despite checking my code multiple times, everything seems to be correct. All the necessary files are saved on my laptop in the same folder for the website. ...

The drop-down menu seems to have disappeared from sight

I'm having an issue with getting a dropdown to appear in my registration form. Everything else in the form is displaying correctly and functioning properly, but the dropdown remains invisible. After searching extensively, I haven't been able to ...

Establish the highest level of recursion permitted when converting a Django model containing a Foreign key into JSON format

I've developed a Django model specifically for Google's App Engine. Model A(): propA = ReferenceProperty(B) Model B(): propB = ReferenceProperty(C) Model C(): propC = ReferenceProperty(B) To handle the data retrieval for the ReferencePr ...

What is the best way to add a button over an image using Tailwind CSS in Next.js?

I've been trying to display a button on top of an image using Tailwind CSS and Next.js, but I'm having trouble getting it to align properly. Here is the code snippet I've been working with: <div> <Image src={projectAiWrite ...