简体   繁体   中英

CSS static files are not working in Django, I am a beginner in Django and main.css properties are not being applied to my store.html

This is added in settings.py


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

urls.py

from django.urls import path
from . import views
from django.contrib.staticfiles.urls import staticfiles_urlpatterns

urlpatterns = [
    path('', views.store, name="store"),
]

urlpatterns += staticfiles_urlpatterns()

views.py

from django.shortcuts import render
from django.template.context import RequestContext

def store(request):
    context ={}
    return render(request, 'store/store.html',context)

store.html

{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'css/main.css' %}">

<h3>store</h3>

<img src="{% static 'images/cart.png' %}">

main.css

body{
    background-color: blue;
}

folder tree

store->store->store.html

static->css->main.css

static->images->cart.png

The code looks clean, but there is one place you clearly overlook. Maybe we can find a solution by comparing the details below with your project.

settings.py

INSTALLED_APPS = [.., 
                  'your_app',]  
...

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',
            ],
        },
    },
]

...

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

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'media') 

urls.py

    urlpatterns = [
        path('admin/', admin.site.urls),
        path('', IndexView.as_view(),name='index'),
    ]
    
    if settings.DEBUG:
        urlpatterns = urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
        urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

models.py

class Task(models.Model):
    user = models.ForeignKey("auth.User", on_delete=models.CASCADE)  
    title = models.CharField(max_length=150)
    content = RichTextField()
    created_date = models.DateTimeField(auto_now_add=True)  
    slug = models.SlugField(editable=False)

    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        self.slug = slugify(self.title)
        super(Task, self).save(*args, **kwargs)

views.py

    class IndexView(ListView):
        template_name = 'task/index.html'
        model = Task
        context_object_name = 'task'
    
        # paginate_by = 7
    
        def get_context_data(self, *, object_list=None, **kwargs):
            context = super(IndexView, self).get_context_data(**kwargs)
            return context

If you want to use static files in your html file, you must specify as follows:

.html

{% load static %}

      ....
      <script src="{% static 'css/bootstrap.min.css' %}"></script>
      <script src="{% static 'js/bootstrap.min.js' %}"></script>

Templates Folder Tree => templates -> task -> index.html

Static Folder Tree => static -> css -> file.css => static -> css -> file.css

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