skip to Main Content

HTML file is working well. But it’s not linking with CSS, what I make in CSS simply does not work.

HTML PAGE

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TheWebPub</title>
    <link rel="stylesheet" href="stylepage.css">
</head>
<body>
    {% if name %}
    <h1 class='title'>Hello {{name}}. </h1>
    {% else %}
    <h1>Hello world.</h1>
    {% endif %}

    <p>Thank you for being here in my website, it's my first one. I'm creating this website with django/python.</p>
</body>
</html>

everything seems to be ok. it’s my views.py file in my django project

from django.shortcuts import render
from django.http import request

# Create your views here.

def say_hello(request):
    return render(request, 'index.html', {'name':'Adryan'})

2

Answers


  1. You can not pass a reference to a file in the templates directory, indeed a browser has no access to this: the templates are opened by the webserver, and then rendered and the result is often then passed as response, as is here the case.

    What you do to work with static (or media) files is store these in the static/ root that is at the same level as the manage.py file. In DEBUG = True mode, you can Django serve static (and media) files by adding these to the root urls.py:

    from django.conf import settings
    from django.conf.urls.static import static
    
    urlpatterns = [
        # the rest of your URLconf goes here …
    ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

    in the template we then pass a reference to this file:

    {% load static %}
    <link rel="stylesheet" href="{% static 'stylepage.css' %}">

    In production, you will have to configure the webserver, like nginx or apache to serve static files.

    For more information, see the How to manage static files section of the documentation.

    Login or Signup to reply.
  2. Well. that’s not the correct way to store css files in django. You should store css in static directory.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search