Django подключить css файл

How to manage static files (e.g. images, JavaScript, CSS)¶

Websites generally need to serve additional files such as images, JavaScript, or CSS. In Django, we refer to these files as “static files”. Django provides django.contrib.staticfiles to help you manage them.

This page describes how you can serve these static files.

Configuring static files¶

  1. Make sure that django.contrib.staticfiles is included in your INSTALLED_APPS .
  2. In your settings file, define STATIC_URL , for example:
 load static %> img src=" static 'my_app/example.jpg' %>" alt="My image"> 

In addition to these configuration steps, you’ll also need to actually serve the static files.

During development, if you use django.contrib.staticfiles , this will be done automatically by runserver when DEBUG is set to True (see django.contrib.staticfiles.views.serve() ).

This method is grossly inefficient and probably insecure, so it is unsuitable for production.

See How to deploy static files for proper strategies to serve static files in production environments.

Your project will probably also have static assets that aren’t tied to a particular app. In addition to using a static/ directory inside your apps, you can define a list of directories ( STATICFILES_DIRS ) in your settings file where Django will also look for static files. For example:

STATICFILES_DIRS = [ BASE_DIR / "static", "/var/www/static/", ] 

See the documentation for the STATICFILES_FINDERS setting for details on how staticfiles finds your files.

Now we might be able to get away with putting our static files directly in my_app/static/ (rather than creating another my_app subdirectory), but it would actually be a bad idea. Django will use the first static file it finds whose name matches, and if you had a static file with the same name in a different application, Django would be unable to distinguish between them. We need to be able to point Django at the right one, and the best way to ensure this is by namespacing them. That is, by putting those static files inside another directory named for the application itself.

You can namespace static assets in STATICFILES_DIRS by specifying prefixes .

Serving static files during development¶

If you use django.contrib.staticfiles as explained above, runserver will do this automatically when DEBUG is set to True . If you don’t have django.contrib.staticfiles in INSTALLED_APPS , you can still manually serve static files using the django.views.static.serve() view.

This is not suitable for production use! For some common deployment strategies, see How to deploy static files .

For example, if your STATIC_URL is defined as static/ , you can do this by adding the following snippet to your urls.py :

from django.conf import settings from django.conf.urls.static import static urlpatterns = [ # . the rest of your URLconf goes here . ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) 

This helper function works only in debug mode and only if the given prefix is local (e.g. static/ ) and not a URL (e.g. http://static.example.com/ ).

Also this helper function only serves the actual STATIC_ROOT folder; it doesn’t perform static files discovery like django.contrib.staticfiles .

Finally, static files are served via a wrapper at the WSGI application layer. As a consequence, static files requests do not pass through the normal middleware chain .

Serving files uploaded by a user during development¶

During development, you can serve user-uploaded media files from MEDIA_ROOT using the django.views.static.serve() view.

This is not suitable for production use! For some common deployment strategies, see How to deploy static files .

For example, if your MEDIA_URL is defined as media/ , you can do this by adding the following snippet to your ROOT_URLCONF :

from django.conf import settings from django.conf.urls.static import static urlpatterns = [ # . the rest of your URLconf goes here . ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) 

This helper function works only in debug mode and only if the given prefix is local (e.g. media/ ) and not a URL (e.g. http://media.example.com/ ).

Testing¶

When running tests that use actual HTTP requests instead of the built-in testing client (i.e. when using the built-in LiveServerTestCase ) the static assets need to be served along the rest of the content so the test environment reproduces the real one as faithfully as possible, but LiveServerTestCase has only very basic static file-serving functionality: It doesn’t know about the finders feature of the staticfiles application and assumes the static content has already been collected under STATIC_ROOT .

Because of this, staticfiles ships its own django.contrib.staticfiles.testing.StaticLiveServerTestCase , a subclass of the built-in one that has the ability to transparently serve all the assets during execution of these tests in a way very similar to what we get at development time with DEBUG = True , i.e. without having to collect them using collectstatic first.

Deployment¶

django.contrib.staticfiles provides a convenience management command for gathering static files in a single directory so you can serve them easily.

    Set the STATIC_ROOT setting to the directory from which you’d like to serve these files, for example:

STATIC_ROOT = "/var/www/example.com/static/" 
$ python manage.py collectstatic

Learn more¶

This document has covered the basics and some common usage patterns. For complete details on all the settings, commands, template tags, and other pieces included in django.contrib.staticfiles , see the staticfiles reference .

Additional Information

Support Django!

Contents

Browse

You are here:

Getting help

FAQ Try the FAQ — it’s got answers to many common questions. Index, Module Index, or Table of Contents Handy when looking for specific information. django-users mailing list Search for information in the archives of the django-users mailing list, or post a question. #django IRC channel Ask a question in the #django IRC channel, or search the IRC logs to see if it’s been asked before. Django Discord Server Join the Django Discord Community. Official Django Forum Join the community on the Django Forum. Ticket tracker Report bugs with Django or Django documentation in our ticket tracker.

Download:

Offline (Django 4.2): HTML | PDF | ePub
Provided by Read the Docs.

Источник

Как подключить CSS (хотя бы один файлик) в django?

Я уже пересмотрел И изучил больше 10 статей. Документации перечитал 3 раза.
Есть вот это:
STATIC_URL = ‘/static/’
Как я понимаю это относительный путь в django к моим статическим файлам.
Далее, есть вот это:

INSTALLED_APPS = [ 'products', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ]

Сверху подключаю статику, вот это я понимаю. Далее в подключаем опять статик урл и оно должно найти мой файлик main.CSS.
Но тупо ниче не работает, ошибка вот такая.
5cb0363b13960734424287.png
Структура проекта вот такая:
5cb03689ee1f2018481806.png:c
Все подключаю в файле base.html
Дорогие люди, спасибо большое что прочитали этот бред по подключение файлика в джанго. Спасибо, за любую помощь.

Простой 17 комментариев

5cb0380f5485d522215997.png

Pavel Denisov, тоже самое.
Проект перезагрузил, файл base.html в котором все подключается обновил тоже.

5cb038a61b9f9295337341.png

Pavel Denisov,

STATIC_URL — это не относительный путь к файлам, это абсолютный URL. Путь к файлам задаёт STATIC_ROOT .

STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), '/что-тотам/vitalik/static/',

в settings.py есть и правильный?

urlpatterns = [ … ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

STATIC_ROOT уже для деплоя

Pavel Denisov, да. Запускаю через runserve. Если имеет значение я вроде не устанавливал ENV, но INCLUDE работает.

STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), '/что-тотам/vitalik/static/',
""" Django settings for vitalik project. Generated by 'django-admin startproject' using Django 2.1.3. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, . ) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'products', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'vitalik.urls' TEMPLATES = [ < 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': < 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], >, >, ] WSGI_APPLICATION = 'vitalik.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = < 'default': < 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), >> # Password validation # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ < 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', >, < 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', >, < 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', >, < 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', >, ] # Internationalization # https://docs.djangoproject.com/en/2.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images)2 # https://docs.djangoproject.com/en/2.1/howto/static-files/ STATIC_URL = '/static/'

Источник

Читайте также:  Html zero width space
Оцените статью