首页 > 解决方案 > 样式表格式在 Django 项目中不起作用

问题描述

我有一个链接样式表的 HTML 文件,如下所示:

 <link rel="stylesheet" href="css/bootstrap.min.css">
 <link rel="stylesheet" href="css/font-awesome.min.css">
 <link rel="stylesheet" href="css/animate.css">
 <link rel="stylesheet" href="css/owl.carousel.css">
 <link rel="stylesheet" href="css/owl.theme.default.min.css">

index.html位于项目的根目录,因此当我打开它时,页面按预期格式化。

我试图将此 css 代码复制到我的 Django 项目中。我将css文件夹放在项目根目录中。上面的 html 代码在里面templates/base.html,我python manage.py runserver从项目根目录运行。当我这样做时,格式不起作用。我尝试了类似的东西href="css/bootstrap.min.css"/full/path/to/css/bootstrap.min.css但它们没有用。我也试过<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">哪个有效。

如何正确引用 Django 项目文件夹中的样式表?

附加信息。

我网站上的任何图像都存储在 AWS 存储桶中。我想我记得读过一些建议静态文件也可能托管在那里的东西。这是我的摘录。settings.py其中是否有可能导致冲突的内容?

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/

STATIC_URL = '/static/'

AUTH_USER_MODEL = 'users.CustomUser'

LOGIN_REDIRECT_URL = 'home'
LOGOUT_REDIRECT_URL = 'home'

CRISPY_TEMPLATE_PACK = 'bootstrap4'

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
EMAIL_HOST = 'smtp.sendgrid.com'
EMAIL_HOST_USER = 'apikey'
EMAIL_HOST_PASSWORD = 'password'
EMAIL_PORT = 587
EMAIL_USE_TLS = True


MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

AWS_STORAGE_BUCKET_NAME = 'lcc-media'
AWS_S3_REGION_NAME = 'eu-west-1'  # e.g. us-east-2
AWS_ACCESS_KEY_ID = 'Access Key'
AWS_SECRET_ACCESS_KEY = 'Secret Key'

# Tell django-storages the domain to use to refer to static files.
AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME

# Tell the staticfiles app to use S3Boto3 storage when writing the collected static files (when
# you run `collectstatic`).
STATICFILES_LOCATION = 'static'
STATICFILES_STORAGE = 'custom_storages.StaticStorage'

# Tell the media app to use S3Boto3 storage when writing the media files
MEDIAFILES_LOCATION = 'media'
DEFAULT_FILE_STORAGE = 'custom_storages.MediaStorage'

# To deal with this: UserWarning: The default behavior of S3Boto3Storage is insecure and will change in django-storages
# 2.0. By default files and new buckets are saved with an ACL of 'public-read' (globally publicly readable). Version 2.0
# will default to using the bucket's ACL. To opt into the new behavior set AWS_DEFAULT_ACL = None, otherwise to silence
# this warning explicitly set AWS_DEFAULT_ACL.
# "The default behavior of S3Boto3Storage is insecure and will change "
AWS_DEFAULT_ACL = None

标签: htmlcssdjangodjango-templates

解决方案


您应该在根文件夹中创建一个名为static的文件夹,并将 CSS 文件夹放入其中。

使用以下方式引用您的静态文件:

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

推荐阅读