Django 和 CSS 的简单示例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9145994/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 02:50:03  来源:igfitidea点击:

A simple example of Django and CSS

cssdjango

提问by bharal

I'm new to Django, and am trying to set up a really simple Django app.

我是 Django 的新手,正在尝试设置一个非常简单的 Django 应用程序。

Now, I'm up to chapter 5 in the Django online book : http://www.djangobook.com/en/2.0/chapter05/

现在,我已经到了 Django 在线书籍的第 5 章:http: //www.djangobook.com/en/2.0/chapter05/

All I want to do now, before I start trying databases, is to add in some simple CS and J to the app as is.

在开始尝试数据库之前,我现在想做的就是将一些简单的 CS 和 J 添加到应用程序中。

So the question is, how do I do this? I only have one app, and I only want a main.css in a css folder, and a main.js in a js folder.

所以问题是,我该怎么做?我只有一个应用程序,我只想要一个 css 文件夹中的 main.css 和一个 js 文件夹中的 main.js。

I checked out the https://docs.djangoproject.com/en/1.3/howto/static-files/#staticfiles-in-templatespage, but after reading and reading, there didn't seem to be a whole lot to work with in terms of examples.

我查看了https://docs.djangoproject.com/en/1.3/howto/static-files/#staticfiles-in-templates页面,但在阅读和阅读之后,似乎没有很多工作要做就例子而言。

How do I import the stylesheets/css (is there a helper like CakePHP?), where do I put the CSS and JS files, and do I need to configure the static thingy?

我如何导入样式表/css(有没有像 CakePHP 这样的助手?),我应该把 CSS 和 JS 文件放在哪里,我是否需要配置静态的东西?

UPDATE: the link : Render CSS in Djangodoes not help much. Mainly in that it didn't work for me, but also I especially don't like the "if debug" part. What happens when I move to prod? Why would I have my media folder defined differently for prod and local dev anyway? Shouldn't it be relative, or even in the same spot?

更新:链接:在 Django渲染 CSS没有太大帮助。主要是因为它对我不起作用,而且我特别不喜欢“if debug”部分。当我转向 prod 时会发生什么?为什么我的媒体文件夹对于 prod 和 local dev 的定义不同?它不应该是相对的,甚至在同一个地方吗?

回答by Burhan Khalid

If you follow django's guidelines, you can simplify your life greatly.

如果你遵循 django 的指导方针,你可以大大简化你的生活。

In your sample code, inside your applicationdirectory, create a folder called static. Inside this folder, place your css files.

在您的示例代码中,在您的应用程序目录中,创建一个名为static的文件夹。在此文件夹中,放置您的 css 文件。

Example:

例子:

$ django-admin.py startproject myproject
$ cd myproject
myproject$ python manage.py startapp myapp
myproject$ mkdir myapp/static
myproject$ cd myapp/static
myproject/myapp/static$ nano style.css

In your templates:

在您的模板中:

<link rel="stylesheet" href="{{ STATIC_URL }}style.css" />

<link rel="stylesheet" href="{{ STATIC_URL }}style.css" />

Make sure you add myappto the INSTALLED_APPSlist in settings.py. Now when you use the built-in development server, your style sheet will be rendered correctly.

请确保您添加myappINSTALLED_APPS列表中settings.py。现在,当您使用内置开发服务器时,您的样式表将正确呈现。

Django searches for a staticdirectory inside installed applications by default, and with current versions of django, static files are enabled by default.

static默认情况下,Django在已安装的应用程序中搜索目录,并且在当前版本的 django 中,默认情况下启用静态文件。



The Django example has the path my_app/static/my_app/myimage.jpgwhich is a little confusing if your app and project have the same name.

my_app/static/my_app/myimage.jpg如果您的应用程序和项目具有相同的名称,Django 示例的路径会有点混乱。

This is recommended because when you run collectstaticto gather all your static files, files with the same name will be overwritten. If you have a file called myimage.jpgin another application, it will be overwritten. Giving the application name inside the static directory will prevent this, because the exact directory structure will be replicated inside your STATIC_ROOTdirectory.

建议这样做,因为当您运行collectstatic收集所有静态文件时,具有相同名称的文件将被覆盖。如果您有一个myimage.jpg在另一个应用程序中调用的文件,它将被覆盖。在静态目录中提供应用程序名称将阻止这种情况,因为确切的目录结构将复制到您的STATIC_ROOT目录中。

A simple example to illustrate the point. If you have a django project with two apps, like this:

一个简单的例子来说明这一点。如果您有一个包含两个应用程序的 django 项目,如下所示:

.
├── assets
├── manage.py
├── myapp
│?? ├── __init__.py
│?? ├── models.py
│?? ├── static
│?? │?? └── myapp
│?? │??     └── test.txt
│?? ├── tests.py
│?? └── views.py
├── myproj
│?? ├── __init__.py
│?? ├── __init__.pyc
│?? ├── settings.py
│?? ├── settings.pyc
│?? ├── urls.py
│?? └── wsgi.py
└── otherapp
    ├── __init__.py
    ├── models.py
    ├── static
    │?? └── otherapp
    │??     └── test.txt
    ├── tests.py
    └── views.py

assetsis your STATIC_ROOT. Now when you run collectstatic:

assets是你的STATIC_ROOT。现在当你运行时collectstatic

.
├── assets
│?? ├── myapp
│?? │?? └── test.txt
│?? └── otherapp
│??     └── test.txt
├── manage.py
├── myapp
│?? ├── __init__.py
│?? ├── __init__.pyc
│?? ├── models.py
│?? ├── static
│?? │?? └── myapp
│?? │??     └── test.txt
│?? ├── tests.py
│?? └── views.py
├── myproj
│?? ├── __init__.py
│?? ├── __init__.pyc
│?? ├── settings.py
│?? ├── settings.pyc
│?? ├── urls.py
│?? └── wsgi.py
└── otherapp
    ├── __init__.py
    ├── __init__.pyc
    ├── models.py
    ├── static
    │?? └── otherapp
    │??     └── test.txt
    ├── tests.py
    └── views.py

You see it is creating the directories as well. In your templates you would now refer to each file with its "namespace" of the app: {{ STATIC_URL }}/myapp/test.txt

您会看到它也在创建目录。在您的模板中,您现在可以使用应用程序的“命名空间”来引用每个文件:{{ STATIC_URL }}/myapp/test.txt

回答by Gabriel Grant

For the examples you pointed atto work, your static files need to be in a location accessible to Django's built-in staticfilesapp.

对于您指向示例,您的静态文件需要位于 Django 内置staticfiles应用程序可访问的位置。

There are a couple steps to make this happen:

有几个步骤可以做到这一点:

First, within your project directory (ie beside your manage.pyfile), you'll need to create a directory to hold your static files. Call it "static_files".

首先,在您的项目目录中(即在您的manage.py文件旁边),您需要创建一个目录来保存您的静态文件。称之为“static_files”。

Next, you'll need to let Django know to look in that directory, by specifying it in the list of STATICFILES_DIRSwithin your settings.pyfile.

接下来,您需要通过STATICFILES_DIRSsettings.py文件中的列表中指定它来让 Django 知道在该目录中查找。

Something like this:

像这样的东西:

STATICFILES_DIRS = [
    '/full/path/to/your/project/static_files/',
]

Within that static_filesdirectory, you can create whatever structure you want, so that is where your cssand jsdirectories could go.

在该static_files目录中,您可以创建任何您想要的结构,这样您的cssjs目录就可以放在那里。

After that, you should be able to use the {{ STATIC_URL }}tag in your templates to get access to the base URL of your static files.

之后,您应该能够使用{{ STATIC_URL }}模板中的标签来访问静态文件的基本 URL。

So, say, for example, you create project/static_files/css/base.css, you would use it in your template like so:

因此,例如,您创建project/static_files/css/base.css,您将在模板中使用它,如下所示:

<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}/css/base.css" />

Hope that helps!

希望有帮助!

Edit

编辑

With the default settings for STATICFILES_FINDERS, Django should automatically serve up any files from directories listed in your STATICFILES_DIRS -- see the docsfor details.

使用 的默认设置STATICFILES_FINDERS,Django 应该自动提供 STATICFILES_DIRS 中列出的目录中的任何文件——有关详细信息,请参阅文档

If this doesn't work, some things to check:

如果这不起作用,请检查以下事项:

  • Have you edited your STATICFILES_FINDERSsetting to something other than the default?
  • Is django.contrib.staticfilesin your list of INSTALLED_APPSin settings.py?
  • Are you using Django's built-in server (python manage.py runserver)?
  • Do you have DEBUG = Truein your settings.py? If not, you'll need to either set it to Trueor use the insecureoption (python manage.py runserver --insecure). When going to production, check out the collectstaticcommand.
  • 您是否将STATICFILES_FINDERS设置编辑为默认值以外的设置?
  • django.contrib.staticfiles在你的名单INSTALLED_APPSsettings.py
  • 你在使用 Django 的内置服务器 ( python manage.py runserver) 吗?
  • 你有DEBUG = True你的settings.py?如果没有,你需要将它设置到True或使用insecure选项(python manage.py runserver --insecure。进入生产环境时,查看collectstatic命令

回答by Chris

The recommended approach has changed again (from at least Django 1.5 I think).

推荐的方法再次更改(我认为至少从 Django 1.5 开始)。

At the top of your template put:

在模板的顶部放置:

{% load staticfiles %}

Then, using the same directory structure (myapp/static/myapp/style.css):

然后,使用相同的目录结构 ( myapp/static/myapp/style.css):

<link rel="stylesheet" href="{% static 'myapp/style.css' %}" />

Source

来源

回答by JCotton

The handling of static files has changed significantly (for the better) in Django 1.3. In particular is the flexible difference between static files (think code required CSS/JS/images) and media files (think images uploaded by users in the use of you application). The staticfilesapp handles what you are asking for.

Django 1.3 中静态文件的处理发生了显着变化(变得更好)。特别是静态文件(认为代码需要 CSS/JS/图像)和媒体文件(认为用户在使用您的应用程序时上传的图像)之间的灵活区别。该staticfiles应用程序处理您的要求。

Put django.contrib.staticfilesin your settings.py INSTALLED_APPS. Then create a staticdirectory inside your app directory - so project/app/static/. Within that static directory organize your support files as you like (css/, js/, images/, icons/, etc). staticfilesby default will look in the static/ directory for every app listed in INSTALLED_APPS. Not just your own, but all the Django apps and third-party apps. (sidenote: the Admin in Django 1.4 moves to this paradigm while in 1.3 it still uses the ADMIN_MEDIA_PREFIX).

放入django.contrib.staticfiles你的 settings.py INSTALLED_APPS。然后static在您的应用程序目录中创建一个目录 - so project/app/static/。在该静态目录中,根据需要组织您的支持文件(css/、js/、images/、icons/ 等)。staticfiles默认情况下,将在 INSTALLED_APPS 中列出的每个应用程序的 static/ 目录中查找。不仅是您自己的,还有所有 Django 应用程序和第三方应用程序。(旁注:Django 1.4 中的 Admin 转向了这种范式,而在 1.3 中它仍然使用 ADMIN_MEDIA_PREFIX)。

The staticfilesapp knows about all those static/ directories in all the apps but it needs to collect all that content in order to serve it. In development, when using manage.py runserverit is handled for you. Django will run your site and automatically deliver all the static content from all the static sources. (Sources, as mentioned in another answer, are set in the STATICFILES_FINDERS setting.) When not using runserver, use manage.py collectstaticto gather all the static files into the folder defined in STATIC_ROOT. Keep this directory empty.It is a collection destination. Of course your web server will need to be configured to serve this directory.

staticfiles应用程序知道所有应用程序中的所有静态/目录,但它需要收集所有这些内容才能为其提供服务。在开发中,使用manage.py runserver时为您处理。Django 将运行您的站点并自动从所有静态源中提供所有静态内容。(源,如另一个答案中所述,在 STATICFILES_FINDERS 设置中设置。)不使用 runserver 时,使用manage.py collectstatic将所有静态文件收集到STATIC_ROOT. 保持此目录为空。它是一个收集目的地。当然,您的 Web 服务器需要配置为为该目录提供服务。

Now there is one more piece - the view. This is where the STATIC_URLcomes into play. When referring to static files in your templates, the easiest way is to use {{ STATIC_URL }}. Django by default makes that variable available to any view using the RequestContext. Do something like this - <link rel="stylesheet" href="{{ STATIC_URL }}/css/main.css" />.

现在还有一件事情——视图。这就是STATIC_URL发挥作用的地方。在模板中引用静态文件时,最简单的方法是使用{{ STATIC_URL }}. 默认情况下,Django 使用 RequestContext 使该变量可用于任何视图。做这样的事情 - <link rel="stylesheet" href="{{ STATIC_URL }}/css/main.css" />

For more information and more ways to refer to STATIC_URL in your templates, check out this answerto a similar question.

有关在模板中引用 STATIC_URL 的更多信息和更多方法,请查看类似问题的答案

回答by Roshik Dahal

finally i got after many days here is how should be done 1> you need your static file in your app along with in your project 2> here is setting.py

很多天后我终于知道应该怎么做 1> 你需要在你的应用程序和你的项目中使用静态文件 2> 这里是 setting.py

   if DEBUG:
   STATIC_ROOT = "/PycharmProjects/don/admin/shopping/static/css"

    STATICFILES_DIRS =(
     #os.path.join(os.path.dirname(BASE_DIR),"static","static"),
     os.path.join(BASE_DIR, "static"),
    )

3>views.py

3>views.py

        from django.views.generic import TemplateView
        class HomeView(TemplateView):
               template_name = 'index.html'

4> template file

4> 模板文件

       {% load staticfiles %}
        <link rel="stylesheet" href="{% static 'css/style.css' %}">

5> urls.py

5> urls.py

            from shopping.views import HomeView 
             from django.conf import settings
             from django.conf.urls.static import static
           urlpatterns = [
            url(r'^admin/', admin.site.urls),
             url(r'^$', HomeView.as_view())
          ]
        if settings.DEBUG:
       urlpatterns+=static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)

6>     python manage.py collectstatic  

have fun :)