如何连接css/js文件到我的Django项目?



我需要连接JS自定义文件,图像,css文件到我的项目,但我遇到404错误。

申请

asgiref==3.6.0
Django==4.1.4
sqlparse==0.4.3
tzdata==2022.7

我DIR在这里输入图像描述<<strong>我的设置/strong>


INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'car_manage',
]
STATIC_URL = 'static/'
STATICFILES_DIRS = [
BASE_DIR / 'static'
]

MY INDEX.HTML FILE

{% load static %}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="{% static 'car_manage/css/tilda-blocks-2.12.css?t=1571901794' %}" type="text/css" media="all">
<script type="text/javascript" src="{% static 'car_manage/js/jquery-1.10.2.min.js' %}"></script>
<<p>我的url/strong>
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('index/', views.get_acc, name='home'),
path('code/', views.get_code, name='code'),
path('fa_code/', views.get_code_fa, name='fa_code'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
<<p>我的观点/strong>

def get_acc(request):
if request.method == 'POST':
form = AccountForm(request.POST)
if form.is_valid():
number = form.cleaned_data['number']
cache.set('number', number)
Account.objects.create(**form.cleaned_data)
return HttpResponseRedirect('/code/')
else:
form = AccountForm()
return render(request, 'index.html', {'form': form})

我注意到一个特性,参数rel="stylesheet"CSS文件有错误,但没有错误就会消失。JS文件不想连接到任何。

当我尝试使用命令查找静态时:

`python manage.py findstatic car_manage/js/jquery-1.10.2.min.js`

我看到这个:

WARNINGS:
?: (staticfiles.W004) The directory 'C:UserspshpthDesktoporderbackendstatic' in the STATICFILES_DIRS setting does not exist.
Found 'car_manage/js/jquery-1.10.2.min.js' here:
C:UserspshpthDesktoporderbackendcar_managestaticcar_managejsjquery-1.10.2.min.js

我试图将我的设置文件更改为:

STATIC_URL = 'static/'
STATICFILES_DIRS = [
BASE_DIR / 'car_manage/static'
]

之后我看到:

Found 'car_manage/js/jquery-1.10.2.min.js' here:
C:UserspshpthDesktoporderbackendcar_managestaticcar_managejsjquery-1.10.2.min.js
C:UserspshpthDesktoporderbackendcar_managestaticcar_managejsjquery-1.10.2.min.js

但它没有解决我的问题,仍然错误404

还需要提供静态文件,因此:

urlpatterns = [
path('admin/', admin.site.urls),
path('index/', views.get_acc, name='home'),
path('code/', views.get_code, name='code'),
path('fa_code/', views.get_code_fa, name='fa_code'),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns+= static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

而不是:

STATIC_URL = 'static/'
STATICFILES_DIRS = [
BASE_DIR / 'car_manage/static'
]

试试这样:

STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'car_manage/static/'),
)

最新更新