Home > Mobile >  how to use css that's in another file django
how to use css that's in another file django

Time:03-15

this is probably a stupid question. I'm new to django and i was wondering how to use css when the css is in a different file.

right now my file paths look like this:

css: web/static/web/style.css Html: web/templates/web

my Html file looks like this:

{% load static %}

<!--HTML-->
<body>
    <div >
        <a  href="/">Home</a>
        <a href="/donate">Donate</a>
    </div>
</body>

my css looks like this:

    .topnav {
    background-color: #333;
    overflow: hidden;
  }
 
  .topnav a {
    float: left;
    color: #f2f2f2;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
    font-size: 17px;
  }
  
  .topnav a:hover {
    background-color: #ddd;
    color: black;
  }
 
  .topnav a.active {
    background-color: #04AA6D;
    color: white;
  }

how can i get the html to use the css from a different file?

CodePudding user response:

add a <head>…</head>tag and type <link rel="stylesheet" href="static/web/style.css"/> inside the <head>…</head> tag. Make sure the <head>…</head> is outside the <body>…</body> tag. Here is the new code.

<!DOCTYPE html>
<html>
 <head>
  <link rel="stylesheet" href="static/web/style.css"/>
  <!--other head contents like title and meta tag goes here-->
 </head>
 <!--HTML-->
 <body>
    <div >
        <a  href="/">Home</a>
        <a href="/donate">Donate</a>
    </div>
 </body>
</html>

CodePudding user response:

This method works for me.

Create a directory called staticfiles then inside that folder create a css directory.

Then check the settings.py file to make it look like this:

import os

PROJECT_DIR = os.path.dirname(__file__)

DATABASES = {
    'default': {
         'ENGINE': 'django.db.backends.sqlite3', 
         'NAME': os.path.join(PROJECT_DIR, 'myweblabdev.sqlite'),                        
         'USER': '',
         'PASSWORD': '',
         'HOST': '',                      
         'PORT': '',                     
    }
}

MEDIA_ROOT = os.path.join(PROJECT_DIR, 'media')

MEDIA_URL = '/media/'

STATIC_ROOT = os.path.join(PROJECT_DIR, 'static')

STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(PROJECT_DIR, 'staticfiles'),

Then go to the main urls.py file of the project and add this:

from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from myweblab import settings

admin.autodiscover()

urlpatterns = patterns('',
    .......
)   static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

urlpatterns  = staticfiles_urlpatterns()

And then in the html file, add this one and it should work now:

{% load static %}

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