使用django_plotly_dash提供TailwindCSS服务

huangapple go评论76阅读模式
英文:

Serve TailwindCSS with django_plotly_dash

问题

我在Django中使用django-plotly-dash提供的Dash应用,同时使用Tailwind进行整个网站的样式设置。在整个网站中,Tailwind似乎正常工作,但在Dash应用中似乎有一些问题,有时被Bootstrap覆盖。

当我单独运行Dash应用时,我可以正常看到Tailwind的样式,但在Django中嵌入时却看不到。

以下是Django中的视图(以及此基本示例的代码):
使用django_plotly_dash提供TailwindCSS服务

以及在没有Django的情况下运行Dash和Tailwind(用鲜艳的颜色来看差异):
使用django_plotly_dash提供TailwindCSS服务

一些Tailwind样式已经生效,比如Dash布局中的container mx-auto,但其他样式(例如颜色)则似乎被忽略了。

以下是Dash应用的代码,分为layout.pycallbacks.pydashboard.py

layout.py

from dash import dcc, html

layout = html.Div(
    className="bg-green-100 container mx-auto my-auto px-15 py-5",
    children=[
        html.Div(
            className="bg-red-100 py-5",
            children=[
                dcc.Dropdown(
                    id="symbol-input",
                    options=[
                        {"label": "Apple", "value": "AAPL"},
                        {"label": "Tesla", "value": "TSLA"},
                        {"label": "Meta", "value": "META"},
                        {"label": "Amazon", "value": "AMZN"}
                    ],
                    searchable=True,
                    value="AAPL",
                )
            ]),
        html.Div(
            className="max-w-full shadow-2xl rounded-lg border-3",
            id="price-chart"
        )
    ]
)

callbacks.py

from dash import dcc, html
from dash.dependencies import Input, Output
import yfinance as yf
import plotly.express as px

def register_callbacks(app):
    
    @app.callback(
        Output("price-chart", "children"),
        Input("symbol-input", "value"),
    )
    def get_data(symbol):
        df = yf.Ticker(symbol).history()
        fig = px.line(
            x=df.index,
            y=df.Close,
            title=f"Price for {symbol}",
            labels={
                "x": "Date",
                "y": "Price ($)",
            }
            )
        return dcc.Graph(
            id="price-chart-1",
            figure=fig
            )

dashboard.py

from django_plotly_dash import DjangoDash
from .layout import layout
from .callbacks import register_callbacks

app = DjangoDash("Dashboard")
app.css.append_css({"external_url": "/static/css/output.css"})

app.layout = layout
register_callbacks(app)

Tailwind CSS位于/static/css/output.css中,并在base.html中作为样式表链接。为确保在Django中正确工作,我创建了一个简单的主页,并从Tailwind的网站中复制了代码以确认它可以正常使用。再次强调,Tailwind在Dash应用中似乎部分生效,但似乎被覆盖了。

英文:

I have a Dash app in Django being served via django-plotly-dash and I'm using Tailwind for the styling across the site. Tailwind seems to be working everywhere except for the Dash app, where it is kind of working, but seems to be overwritten by the Bootstrap at some points.

I can see the Tailwind styling without any issues if I run the Dash app on its own, but not when embedded in Django.

Here's the view inside Django (and the code for this basic example):
使用django_plotly_dash提供TailwindCSS服务

And here it is (with garish colors to see the difference) while running Dash and Tailwind without Django:
使用django_plotly_dash提供TailwindCSS服务

Some of the Tailwind styling is being applied, such as the container mx-auto bit of the Dash layout, but others (e.g. coloring) are being dropped.

Here's the code for the Dash app, which is split into layout.py, callbacks.py, and dashboard.py:

layout.py:

from dash import dcc, html

layout = html.Div(
    className="bg-green-100 container mx-auto my-auto px-15 py-5",
    children=[
        html.Div(
            className="bg-red-100 py-5",
            children=[
                dcc.Dropdown(
                    id="symbol-input",
                    options=[
                        {"label": "Apple", "value": "AAPL"},
                        {"label": "Tesla", "value": "TSLA"},
                        {"label": "Meta", "value": "META"},
                        {"label": "Amazon", "value": "AMZN"}
                    ],
                    searchable=True,
                    value="AAPL",
                )
            ]),
        html.Div(
            className="max-w-full shadow-2xl rounded-lg border-3",
            id="price-chart"
        )
    ]
)

callbacks.py:

from dash import dcc, html
from dash.dependencies import Input, Output
import yfinance as yf
import plotly.express as px

def register_callbacks(app):
    
    @app.callback(
        Output("price-chart", "children"),
        Input("symbol-input", "value"),
    )
    def get_data(symbol):
        df = yf.Ticker(symbol).history()
        fig = px.line(
            x=df.index,
            y=df.Close,
            title=f"Price for {symbol}",
            labels={
                "x": "Date",
                "y": "Price ($)",
            }
            )
        return dcc.Graph(
            id="price-chart-1",
            figure=fig
            )

dashboard.py:

from django_plotly_dash import DjangoDash
from .layout import layout
from .callbacks import register_callbacks

app = DjangoDash("Dashboard")
app.css.append_css({"external_url": "/static/css/output.css"})

app.layout = layout
register_callbacks(app)

The Tailwind CSS is in /static/css/output.css and is linked as the stylesheet in the base.html. To ensure it's working correctly in Django, I put a simple homepage up and copied code from Tailwind's site to confirm that it works. Again, it's partially coming through in the Dash app, but seems to get overwritten.

答案1

得分: 1

在查看您的存储库后,我认为问题不在于Bootstrap CSS覆盖了Tailwind的CSS,问题在于您定义的类别根本没有被Tailwindcss扫描到。我假设您是使用以下命令生成output.css的:

npx tailwindcss -i ./static/css/input.css -o ./static/css/output.css --watch

如果您是用这个命令来生成CSS,那我能理解问题所在。这是因为您的tailwind.config.js文件如下所示:

...
  content: [
    "./static/css/*.html",
    "./templates/*.html",
    "./static/css/*.js",
  ],
...

您说containermx-auto类被应用,但颜色类(例如bg-green-100bg-red-100)没有被应用,这仅仅是因为containermx-auto类是在"./static/css/*.html", "./templates/*.html", "./static/css/*.js"之一的文件中定义的,而bg-green-100bg-red-100是在这些目录之外的其他目录中定义的(在apps\dashboard\layout.py中定义)。

最简单的解决方法是将需要应用CSS类的目录添加到tailwind.config.js文件中,例如:

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    "./static/css/*.html",
    "./templates/*.html",
    "./static/css/*.js",
    "./apps/**" // 添加这一行
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}

这将添加来自./apps目录或子目录中的任何文件中的所有类别到tailwindcss构建过程中。但不要忘记每次运行服务器时运行tailwindcss命令(就像我之前提到的那个命令一样)。

英文:

After viewing your repository, I think the problem is not that the Bootstrap CSS overrides the tailwind's one, the problem here is that the classes that you defined are simply not scanned by Tailwindcss. I'm going to assume that you generate the output.css using this command:

> npx tailwindcss -i ./static/css/input.css -o ./static/css/output.css --watch

If that's what you did to generate the CSS, then I can understand what's going on here. That's simply because of your tailwind.config.js file looks like this:

...
  content: [
    "./static/css/*.html",
    "./templates/*.html",
    "./static/css/*.js",
  ],
...

You said that container, mx-auto classes are applied, but not the color classes (e.g. bg-green-100, bg-red-100), that's simply because container, mx-auto classes are defined in one of "./static/css/*.html", "./templates/*.html", "./static/css/*.js", while bg-green-100, bg-red-100 are defined in other directory than those directories (it's defined in apps\dashboard\layout.py).

The easiest fix is to add the directories in which CSS classes need to be applied to the tailwind.config.js file, e.g.:

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    "./static/css/*.html",
    "./templates/*.html",
    "./static/css/*.js",
    "./apps/**" // add this line
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}

This will add all classes from any files or any files in ./apps directory or subdirectories to the tailwindcss build process. Don't forget to run the tailwindcss cli command (the one I mentioned earlier) every time you run the server though.

huangapple
  • 本文由 发表于 2023年2月8日 11:50:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/75381208.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定