我有自訂css
和js
檔案、admin.py
和覆蓋的base.html 位於templates/admin/app1/
中,如下圖所示:
django-project |-core | |-settings.py | └-static | └-core | └-admin | └-app1 | |-css | | └-custom.css # Here | └-js | └-custom.js # Here |-app1 | |-models.py | └-admin.py # Here |-app2 └-templates └-admin └-app1 └-base.html # Here
首先,我將自訂css
和js
檔案分別設定為c 中所有管理員
Person
、Animal
和Food
的Media 類別中的css
和endcphpcn phpcnapp1
如下所示,然後我可以將它們應用到所有管理員Person
、Animal
和Food
app1
:
# "app1/admin.py" from django.contrib import admin from .models import Person, Animal, Food @admin.register(Person) class PersonAdmin(admin.ModelAdmin): class Media: css = { 'all': ('core/admin/app1/css/custom.css',) # Here } js = ('core/admin/app1/js/custom.js',) # Here @admin.register(Animal) class AnimalAdmin(admin.ModelAdmin): class Media: css = { 'all': ('core/admin/app1/css/custom.css',) # Here } js = ('core/admin/app1/js/custom.js',) # Here @admin.register(Food) class FoodAdmin(admin.ModelAdmin): class Media: css = { 'all': ('core/admin/app1/css/custom.css',) # Here } js = ('core/admin/app1/js/custom.js',) # Here
但是,上面的解決方案效率不高,所以我在<link ..."admin/css/base.css" %}{% endblock %}">
in base.html
之後設定它們,如下所示,但解決方案如下不起作用:
# "templates/admin/app1/base.html" # ... <title>{% block title %}{% endblock %}</title> <link rel="stylesheet" href="{% block stylesheet %}{% static "admin/css/base.css" %}{% endblock %}"> <link rel="stylesheet" href="{% static "core/admin/app1/css/custom.css" %}"> {# Here #} <script src="{% static 'core/admin/app1/js/custom.js' %}" defer></script> {# Here #} {% block dark-mode-vars %} <link rel="stylesheet" href="{% static "admin/css/dark_mode.css" %}"> # ...
因此,我將base.html
放入templates/admin/
中,如下所示,然後上述解決方案有效,但自訂css
和js
檔案將會套用到所有應用程式中的所有管理員:
django-project |-core | |-settings.py | └-static | └-core | └-admin | └-app1 | |-css | | └-custom.css | └-js | └-custom.js |-app1 | |-models.py | └-admin.py |-app2 └-templates └-admin └-base.html # Here
那麼,如何將自訂css
和js
檔案僅有效地套用到app1
中的所有管理員Person
、 Animal
和Food
嗎?
P粉5459565972024-04-04 12:10:56
我無法使用評論。
STATICFILES_DIRS = [ # add # os.path.join(BASE_DIR, 'core', 'static' ....) ] ....
from django.conf import settings from django.conf.urls.static import static urlpatterns = [ # ... the rest of your URLconf goes here ... ] # add + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
# add STATIC_URL = "static/"
python manage.py collectstatic
https://docs.djangoproject。 com/ja/4.2/howto/static-files/#configuring-static-files