Home > Software engineering >  404 error when getting file in static, django
404 error when getting file in static, django

Time:08-11

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
...

CodePudding user response:

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.

CodePudding user response:

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' %}">
  • Related