简体   繁体   中英

404 error when getting file in static, django

I tried several attempts through googling, but it didn't work. I don't think it was like this when I was working on another Jango project, but I don't know why.

urls.py

from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static

from . import views

urlpatterns = [
    path("admin/", admin.site.urls),

    path("", views.HomeView.as_view(), name = 'home'), #to home.html
    path("blog/", include('blog.urls')),
]
# urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT) 

settings.py

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

STATIC_URL = "static/"
STATICFILES_DIR = (os.path.join(BASE_DIR, 'static'),)
# STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR),"static")

home.html

<img src="{% static 'assets/img/navbar-logo.svg' %}" alt="..." />

directory

Project-folder
|
|__config
|  |__settings.py
|  |__urls.py
|
|__app
|
|__template
|  |__app
|  |  |__bla.html
|  |__home.html
|
|  #bootstrap
|__static
   |__assets
      |__img
...

If you've didn't loaded the static try this in your base.html or the home.html

{% load static %}

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

An Excerpt from the docs .

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.

So, use list of dictionaries and also it is STATICFILES_DIRS not STATICFILES_DIR , you missed S .

Try this:

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

Or this:

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

Make sure that you have loaded the static tag.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM