Django templates with CSS file not working - html

I am learning about templates for my project (I am creating a web app using the Django framework with HTML and CSS). However, I have hit a snag. I did try to link the CSS file to the base HTML file (which is the parent template that my other templates inherit from) and my CSS updates aren't reflecting on the home page to my browser.
Is there a problem with the link? The indentations are okay and there are no errors on my code. I have also tried to rerun my server and nothing. The "main.css" file is in the static subdirectory which is inside the blog directory and my app is called "Brenda's Blog".
The code in my base.html file is below, inclusive of the link linking the main.css file.
My CSS file: blog/static/main.css
{% load static %}
<!-- will load css file from static directory -->
<!DOCTYPE html> {% load static %}
<!-- will load css file from static directory -->
<!DOCTYPE html>
<html>
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="{% static 'blog/main.css' %}">
{% if title %}<!-- django for loop for when the user clicks on to different pages -->
<title>Brenda's Blog - {{ title }}</title>
{% else %}
<title>Brenda's Blog</title>
{% endif %}
</head>
<body>
<!-- added navigation bar with bootstrap css classes to decorate the website -->
<header class="site-header">
<nav class="navbar navbar-expand-md navbar-dark bg-steel fixed-top">
<div class="container">
<a class="navbar-brand mr-4" href="/">Brenda's Blog</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggle" aria-controls="navbarToggle" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarToggle">
<div class="navbar-nav mr-auto">
<a class="nav-item nav-link" href="/">Home</a>
<a class="nav-item nav-link" href="/about">About</a>
</div>
<!-- Navbar Right Side -->
<div class="navbar-nav">
<a class="nav-item nav-link" href="#">Login</a>
<a class="nav-item nav-link" href="#">Register</a>
</div>
</div>
</div>
</nav>
</header>
<main role="main" class="container">
<div class="row">
<div class="col-md-8">
{% block content %}{% endblock %}
</div>
<div class="col-md-4">
<div class="content-section">
<h3>Our Sidebar</h3>
<p class='text-muted'>You can put any information here you'd like >
<ul class="list-group">
<li class="list-group-item list-group-item-light">Latest Posts</li>
<li class="list-group-item list-group-item-light">Announcements</li>
<li class="list-group-item list-group-item-light">Calendars</li>
<li class="list-group-item list-group-item-light">etc</li>
</ul>
</p>
</div>
</div>
</div>
</main>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script>
</body>
</html>

Welcome to Stackoverflow.
Make sure your settings.py file have the following configuration.
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_DIR = os.path.join(BASE_DIR,'static')
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
STATIC_DIR,
]
Then run,
python manage.py collectstatic
This command will collect static files from your all of your django applications into a single directory called staticfiles which will also benefit you when you will be deploying your project.
Then load staticfiles in the beginning of your template.
{% load staticfiles %}
Don't forget to clear cache of your browser, press ctrl+F5 to ignore the cached content when refreshing.

First, clear your cache and hard refresh the browser. If it doesn't work then go for the following steps.
Check your settings.py file for correct configurations to access the static files. The code should look like this in the settings.py file.
STATIC_URL = '/static/'
STATIC_ROOT= os.path.join(BASE_DIR,'static')
Then your project structure should be like
app > static > app name(folder name same as app name) > main.css
So if your app name is blog. Then the structure should be like
blog > static > blog > main.css
After doing the changes hard refresh your browser, clear cache, go to Network tab ( clicking inspect element) and check whether you are getting CSS file on request and all the changes are getting reflected.

You should replace
{% load static %}
<!-- will load css file from static directory -->
<!DOCTYPE html> {% load static %}
<!-- will load css file from static directory -->
<!DOCTYPE html>
with
{% load static %}
<!DOCTYPE html>

Related

Flask + Jinja2: left-aligning a table below a nav-bar

I am working on a web page displaying a table below a navigation bar. The table on the page is generated from data coming from a database. The page as such does what it is supposed to do, but the table hosting the data is not left aligned on the page, but has a lot of white space to its left.
The Python/Flask-part of the code looks like this, data from the database comes as pandas DataFrame:
from flask import Flask, render_template
import DBConnector
from jinja2 import Environment
import pandas as pd
app = Flask(__name__)
app.jinja_options = {'lstrip_blocks': True, 'trim_blocks': True}
app.create_jinja_environment()
#app.route('/')
def index():
connector = DBConnector()
df: pd.DataFrame = connector.getData()
return render_template('index.html', tables=[df.to_html(classes='data', header=True)])
I borrowed the index.html code from a Stackoverflow post:
{% extends 'base.html' %}
{% block content %}
<h1>{% block title %}Table Viewer{% endblock %}</h1>
{% for table in tables %}
{{ table|safe }}
{% endfor %}
{% endblock %}
which extends the file base.html:
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>{% block title %} {% endblock %}</title>
</head>
<body>
<nav class="navbar navbar-expand-md navbar-light bg-light">
<a class="navbar-brand" href="{{ url_for('index')}}">Home</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="#">About</a>
</li>
</ul>
</div>
</nav>
<div class="container" align="left">
{% block content %}
{% endblock %}
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
The output looks like this:
How can I remove the large white space to the left of the table?

I am trying to work with Django CMS and templates. but get an error while editing a template

I want the css and js file to load.
It will display the error "Invalid block tag on line 15: 'static'. Did you forget to register or load this tag?" is displayed. but I have created the data correctly. does anyone see the error in my html file?
Here is the code where I suspect the problem
<!-- Bootstrap core CSS -->
<link href="{% static 'vendor/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="{% static 'css/modern-business.css' %}" rel="stylesheet">
Here is the complete code
{% load cms_tags menu_tags sekizai_tags %}
<!DOCTYPE html>
<html lang="{{ LANGUAGE_CODE }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="{% page_attribute 'meta_description' %}">
<meta name="author" content="Life Imaging Services GmbH">
<title>{% page_attribute "page_title" %}</title>
<!-- Bootstrap core CSS -->
<link href="{% static 'vendor/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="{% static 'css/modern-business.css' %}" rel="stylesheet">
{% render_block "css" %}
</head>
<body>
{% cms_toolbar %}
<!-- Navigation -->
<nav class="navbar fixed-top navbar-expand-lg navbar-dark bg-dark fixed-top">
<div class="container">
<a class="navbar-brand" href="index.html">Start Bootstrap</a>
<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse"
data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false"
aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
{% show_menu 0 100 100 100 %}
</ul>
</div>
</div>
</nav>
<!-- Page Content -->
<div class="container">
<!-- Page Heading/Breadcrumbs -->
<h1 class="mt-4 mb-3">Full Width
<small>Subheading</small>
</h1>
<ol class="breadcrumb">
<li class="breadcrumb-item">
Home
</li>
<li class="breadcrumb-item active">Full Width</li>
</ol>
<p>Most of Start Bootstrap's unstyled templates can be directly integrated into the Modern Business template. You
can view all of our unstyled templates on our website at
https://startbootstrap.com/template-categories/unstyled.
</p>
</div>
<!-- /.container -->
<!-- Footer -->
<footer class="py-5 bg-dark">
<div class="container">
<p class="m-0 text-center text-white">Copyright © Your Website 2020</p>
</div>
<!-- /.container -->
</footer>
<!-- Bootstrap core JavaScript -->
<script src="{% static 'vendor/jquery/jquery.min.js' %}></script>
<script src="{% static 'vendor/bootstrap/js/bootstrap.bundle.min.js' %}></script>
{% render_block "js" %}
</body>
</html>
That is because you are not loading the static.
What to do?
Go to the top of the file
Add this {% load static %}
Now you can use the static because you have loaded it.
Read more about it here: https://docs.djangoproject.com/en/3.0/howto/static-files/
{% load static %}
You need to include this tag at the top of the page.
See more info here:
https://docs.djangoproject.com/en/3.0/howto/static-files/

Django Bootstrap Dropdown Menu not working

Building my first Django app from a tutorial, following the instructions pretty much verbatim but my navbar dropdown menu is not working no matter what I try, so unable to log out or change password from the navbar.
I am very new to js, but some things I have tried:
Experimenting w different browsers (doesn't work for Safari or Chrome)
Have looked at similar questions and implemented those techniques but it's still not working (linking to js in the head, making sure to link to js/popper/bootstrap in the correct order, etc.):
django bootstrap dropdown not working
Have also attempted to create static folders in pages/static/js and pages/static/css but that looks like it may be for more advanced styling than what we're going for here.
Bootstrap template not working correctly Django
Template file/directory below. Issue is between lines 55 and 68 (div class="collapse navbar-collapse")
Thanks in advance for the help.
<!-- templates/base.html -->
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/\ 1.14.3/
umd/popper.min.js"
integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAKl8WvCWPIPm49"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/\ js/bootstrap.min.js"
integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ\ 6OW/JmZQ5stwEULTy"
crossorigin="anonymous"></script>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
crossorigin="anonymous">
<!-- <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script> -->
<title>{% block title %}Newspaper App{% endblock title %}</title>
</head>
<body>
<nav class="navbar navbar-expand-md navbar-dark bg-dark mb-4">
<a class="navbar-brand" href="{% url 'home' %}">Newspaper</a>
{% if user.is_authenticated %}
<ul class="navbar-nav mr-auto">
<li class="nav-item">+ New</li>
</ul>
{% endif %}
<button class="navbar-toggler" type="button" data-toggle="collapse"
data-target="#navbarCollapse" aria-controls="navbarCollapse"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarCollapse">
{% if user.is_authenticated %}
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link dropdown-toggle" href="#" id="userMenu"
data-toggle="dropdown" aria-haspopup="true"
aria-expanded="false">
{{ user.username }}
</a>
<div class="dropdown-menu dropdown-menu-right" aria-labelledby="userMenu">
<a class="dropdown-item" href="{% url 'password_change'%}">Change password</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="{% url 'logout' %}"> Log Out</a>
</div>
</li>
</ul>
{% else %}
<form class="form-inline ml-auto">
<a href="{% url 'login' %}" class="btn btn-outline-secondary">
Log In</a>
<a href="{% url 'signup' %}" class="btn btn-primary ml-2">
Sign up</a>
</form>
{% endif %}
</div>
</nav>
<div class="container">
{% block content %}
{% endblock content %}
</div>
</body>
</html>
I copied your code and had the same problem but after swapping the bootstrap.js script for a different one it started working.
The problem was a backslash in the bootstraps js URL.
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/\ js/bootstrap.min.js"
integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ\ 6OW/JmZQ5stwEULTy"
crossorigin="anonymous"></script>
After https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/ there is \ js/bootstrap.min.js
but it should be https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js
So when we switched to the newest js it fixed the problem but that js is still valid if you fix the path.
https://getbootstrap.com/docs/4.4/getting-started/introduction/

Unable to set background image in Django

So I have a base.html file, to which I am trying to add a background image. This base.html file is inherited in all other system files, and I am hoping that adding the background image to base.html will automatically add the background image in all those files which inherit it.
I have a master.css file in my static/css path, and I am trying to add the background image to it by:
body{
background-image: url(./background.jpeg);
}
I have put the image in same folder as the master.css.
I am also attaching a screenshot of my file structure.
Where am I going wrong? Any help is appreciated. Thank you.
EDIT 1:
adding my base.html where I am importing the css file.
<!DOCTYPE html>
{% load static %}
<html>
<head>
<meta charset="utf-8">
<title>Coupon Portal</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<!-- Optional theme -->
<!-- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous"> -->
<!-- Alternative to Bootstrap 3 Glyphicons -->
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
<link rel="stylesheet" href="{% static 'couponSystem/css/master.css'%}">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<script>
</script>
</head>
<body>
<nav class="navbar navbar-expand-lg bg-dark mynav" role="navigation" id="navbar">
<div class="container">
<div class="navbar-nav align-items-center">
<a class="navbar-brand mynav" href="{% url 'home' %}">The Coupon Portal</a>
</div>
<div class="navbar-nav ml-auto">
{% if user.is_authenticated %}
<a class="nav-item nav-link" href="{% url 'accounts:logout' %}" class="btn btn-simple">Log out</a>
{% else %}
<a class="nav-item nav-link" href="{% url 'accounts:login' %}" class="btn btn-simple">Log in</a>
<a class="nav-item nav-link" href="{% url 'accounts:signup' %}" class="btn btn-simple">Sign up</a>
{% endif %}
</div>
</div>
</nav>
<div class="container mycontent">
{% block content %}
{% endblock %}
</div>
</body>
</html>
You are missing quotation marks, try it like this:
body{
background-image: url("background.jpeg");
}
I suspect that the problem could be due to access permissions on the folder where the .jpeg image is placed.
If the image can be opened from browser directly as a url (http://host-name/static/css/background.jpeg), then the background-image will work fine.
Replace this, I thnik it will work.
body{
background-image: url("./static/css/background.jpeg");
}

How to change the background picture and content of each pages in django way

I have a base.html file and 10+ other pages with different background picture and contents. I tried using {% extends "base.html" %} , but how can I change my background picture and content in each pages if am doing so? Please help me on this case. Thanks in advance.
EDIT
My directory:
And my base.html:
{% load staticfiles %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="../../favicon.ico">
<title>Parasol.</title>
<!-- Bootstrap core CSS -->
<link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet">
<link href="{% static 'css/navbar-static-top.css' %}" rel="stylesheet">
<link href="{% static 'css/style.css' %}" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="navbar-static-top.css" rel="stylesheet">
<script src="../../assets/js/ie-emulation-modes-warning.js"></script>
<style>
{% block additional_styles %}
body {
background:url(static/custom/img/voice.jpg) no-repeat center center fixed;
}
</style>
{% endblock %}
</head>
<body>
<nav class="navbar navbar-default navbar-static-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<a class="navbar-brand" href="{% url "home" %}">Parasol.</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
Photos <span class="caret"></span>
<ul class="dropdown-menu">
<li>Action</li>
</ul>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li>Timeline</li>
<li class="active">Quotes<span class="sr-only">(current)</span></li>
<li>Friends</li>
</ul>
</div><!--/.nav-collapse -->
</div>
</nav>
<div class="container">
<div class="jumbotron">
<h1>Just her and the revolution</h1>
<p>
Let's take a trip..
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="../../dist/js/bootstrap.min.js"></script>
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<script src="../../assets/js/ie10-viewport-bug-workaround.js"></script>
</body>
</html>
There are many different ways to do that, which are dependent on the type of the content, your project and the templates structure. Regarding background picture, you can simply add block to your base.html:
{% block additional_styles %}
<style>
body {
background-image: url(images/base.jpg);
}
</style>
{% endblock %}
and then in your template_1.html (which is the template for some other pages):
{% extends 'base.html' %}
{% block additional_styles %}
<style>
body {
background-image: url(images/1.jpg);
}
</style>
{% endblock %}
In addition to above answer add below tags in base.html
{% block additional_styles %}
{% endblock %}
in your <head> tag.
Like (in base.html)
<head>
{% block additional_styles %}
{% endblock %}
</head>
You may do that by overriding bootstrap's predefined styles either as in css file or extra styles section or superseding a specific sections styles, e.g.
<nav class="navbar navbar-expand-md navbar-dark fixed-top" style="background-color: #32CD32;">
<nav class="navbar navbar-expand-md navbar-dark fixed-top" style="background-image: url({% static "img/ok.jpg" %}); background-repeat: repeat-x;">