Django Invalid block tag: 'static' - python

I have this in the <head> of my base.html.
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static "myStyleSheet.css" %}">
and I get error Invalid block tag: 'static'
Within INSTALLED_APPS I've included
'django.contrib.staticfiles',
and I've included within settings.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(os.path.dirname(__file__), "static/")
Why do I get the load error?

the actual problem here, I'm very sorry to say, was that within my app.yaml file I had specified a different directory for the static files and it seemed to be overriding everything else. Once removed, all sorted.

Do you have the django.core.context_processors.static context processor in your TEMPLATE settings? Here's a sample:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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',
'django.core.context_processors.static',
],
},
},
]
You can add it there or use { %load static %} in your template.

Use {% load static %} or {% load static from staticfiles %}
Please check https://stackoverflow.com/a/27516199/263989

It seems that everything is fine. Check if static word is written using only English letters, it may be because of this.

You can change
href="{% static "myStyleSheet.css" %}"
to
href="{% static 'myStyleSheet.css' %}"
Single quotes for myStyleSheet.css

Many answers are here but try this too. I'm going to describe everything. forget and clear anything added before and just follow these hints
1- in your settings.py and INSTALLED_APPS you should have
'django.contrib.staticfiles',
and also STATIC_URL = '/static/'. by default it's exists in the end of your file but check again yourself
2- in settings.py your TEMPLATES should be like as follow
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',
'django.core.context_processors.static',
],
},
},
]
Do not try to add this again ! just check for mistakes
3- static folder must be in the application directory not your main directory of project
project
-application
-migrations
-static
-templates
4- in static folder create sub directories for your files for example
project
-application
-static
-css
-js
-img
-....
-....
and put your files to specific folder
5- now in your HTML file add {% load staticfiles %} first of file and everywhere you need a static file try to add that like as follow
<link href="{% static "css/myStyleSheet.css" %}" rel="stylesheet">
or
<link rel="icon" href="{% static "img/favicon.png" %}">
If you follow these hints, everything should be OK. test and report again

Related

python built in server not loading css file

Why does not it work in Django? There is error in the browser like that.
its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
In file html there is :
<link rel="stylesheet" href="{% static 'nowy.css' %}">
In settings.py it looks like:
STATIC_URL = '/static/'
Dirs are: app > static > nowy.css
I can't find where is the mistake.
this can be caused by your settings static variables, or your addressing to your css file.
first try to check settings.
did you include STATICFILES_DIRS ?
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
and also try checking template settings.
did you include loader?
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'APP_DIRS': False,
'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',
],
'loaders': [
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
],
},
},
]
now try to check the path to your css file.
project
app_name
static
app_name
style.css
in your html it would be like this
{% load static %}
<link rel="stylesheet" href="{% static "app_name/style.css" %}">

Why will the css in my django project not render?

I'm still just playing around with Django and cannot figure out what I am doing wrong with my CSS file. My HTML works but not the CSS. I'm guessing it has something to do with settings.py or some special "Django code" I'm not using. Here is the code for my HTML (what I am guessing is the relevant code to show).
Here is my HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>home</title>
<link rel="stylesheet" type="text/css" href="../css/styles.css"/>
</head>
<body>
<h3>HELLO WORLD!</h3>
</body>
</html>
Here is my settings.py:
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',
],
},
},
]
WSGI_APPLICATION = 'ecommerce005.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
Here is my urls.py:
from django.conf.urls import url
from django.contrib import admin
from .views import home_page
urlpatterns = [
url(r'^$', home_page),
url(r'^admin/', admin.site.urls),
]
Here is my views.py:
from django.http import HttpResponse
from django.shortcuts import render
def home_page(request):
return render(request, "index.html", {})
The order of my file are as follows:
'src' directory:
1) 'css' folder holds my styles.css file
2) 'projectname' folder contains all of my django files shown above
3) 'templates' folder holds my index.html file
Please be as specific as possible. I found sources online but they seemed too vague for me to find a solution. I appreciate your help.
Configure static files in settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS=[
(os.path.dirname(BASE_DIR),"static"),
]
STATIC_ROOT = (os.path.dirname(BASE_DIR),"static_files")
In Templates,(ie HTML file)
{% load static %}
<html>
....
<link href="{% static 'styles/style.css' %}" rel="stylesheet" media="screen, print" type="text/css">
Directory Structure
-ProjectFolder
--|static
----|styles
------|styles.css
You need to setup a 'STATIC_ROOT' in the settings.py
STATIC_URL = '/staticfiles/'
STATIC_ROOT = os.path.join(BASE_DIR, '/static/')
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
If DEBUG=False, you need to setup your proxy server such as nginx to serve these staticfiles
This link can explain it further.
Wootton, as was said, you need to setup your static_root on settings.py, after that you can just call your css
<link type="text/css" rel="stylesheet" href="{{ STATIC_URL }}css/style-responsive.css">
but before/after setup the static_root you need to create a folder named static and serve your css in there.
I think this will help you!

Displaying variable from tags file or context_processors in Django Template

According to my other question about : Handle dynamic staticfiles path with Django
I am not finding the way to solve my problem. I would like to insert in my HTML template a variable corresponding to a Django query.
I already used tags in order to allow some parts depending on users' groups.
My tags.py file looks like :
from django import template
from django.contrib.auth.models import Group
from Configurations.models import Theme
register = template.Library()
#register.filter(name='has_group')
def has_group(user, group_name):
group = Group.objects.get(name=group_name)
return group in user.groups.all()
#register.assignment_tag
def GetTheme(Theme):
mytheme = Theme.objects.values_list('favorite_theme').last()
return mytheme
And my HTML template looks like :
<!DOCTYPE html>
<html>
<head>
{% load staticfiles %}
{% load static %}
{% load user_tags %}
<title> DatasystemsEC - Accueil </title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="{% get_static_prefix %}{{ mytheme }}/css/Base_Accueil.css"/>
The goal is to pick up the variable mytheme in my tags.py file and insert it in my html template.
In return, I'm getting all the time :
#Look double // in my url
http://localhost:8000/static//css/Base_Accueil.html
#I should get
http://localhost:8000/static/{{ mytheme }}/css/Base_Accueil.html
But, after a long moment to search a solution and with the generosity from #DanielRoseman in my previous post, I don't find the solution.
Maybe someone had indices or ideas ?
Thank you
I found the solution based on different answers and I will explain what I've done. This solution works for me with Django 1.10 :
First step : Modify settings.py file
I modified my settings.py file and more precisely TEMPLATES PART. For the moment, this modification is just for Accueil Application but I will extend this process to all applications :
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'debug' : DEBUG,
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'myapp.context_processors.context_processors_name_function'],
},
},
]
With the following example, the last line will be written like this :
# 'myapp.context_processors.context_processors_name_function'
'Accueil.context_processors.GetTheme'
Second step : Create context_processors.py file in my application
I created this new file in my application part. As above, it will be extend to others applications :
from django.conf import settings
from Configurations.models import Theme
def GetTheme(request):
return {'mytheme' : Theme.objects.values_list('favorite_theme').last()[0].encode("ascii")}
Third step : Modify my Base.html for Accueil application
I have a base template which manage my Accueil application. I have to write header like this is I want to take account the context_processors variable :
{% load static %}
<link rel="stylesheet" type="text/css" href="{% get_static_prefix %}{{ mytheme }}/css/Base_Accueil.css"/>
Through this way, I can pick up the last row from my Theme table and put the variable in {{ mytheme }}. Then, I created my good theme url. Now, Django will search all css file in the good repository.
From now, when I fill the formulary with a choice between two themes : Datasystems and Cameroun and validate my choice, the new theme is taken account and the global background-color change due to my theme choice !
Hopfully my answer will help others programmers !
Thank you for all :)
you can write custom context_processors.
settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'web', 'templates'),],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.media',
'django.core.context_processors.static',
'django.contrib.messages.context_processors.messages',
'myapp.contextprocessor.mytheme',
],
},
},
]
contextprocessor.py
def mytheme(request):
return {'mytheme': 'red'}

How can i change django admin to rtl style

First of all i'm new to django . and i'm amazing from this cool framework (not in database part and mysql connector)
And When i looking to django admin style folder in css folder ,
i see rtl css , but now i don't know how can i change admin style to rtl .
This is screen shot from my folders
Thank's
Try setting your language code in settings:
LANGUAGE_CODE = 'fa-ir'
for further reading on translating, rtl, changing date format and other localization things read this django doc.
Django looks at the TEMPLATES setting to find order to check for templates to render. As such, you can add rtl.css to the head of the base admin template in order to load the right-to-left css.
In a templates sub-directory of your main project directory, create dir admin and file base.html. Copy the contents of 'django/contrib/admin/templates/base.html' from Django's source to the newly created file.
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')], # <- add this line
'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',
],
},
},
]
In the template, you'll see {% block extra_head %}{% endblock %}. Insert the stylesheet link here, like this-
{% block extra_head %}
<link rel='stylesheet' href='{% static 'admin/css/rtl.css' %}' />
{% endblock %}
Now rtl.css will be loaded whenever any admin page is loaded.

Django Global base.html template

I am new to Django. I am using Django 1.8.6 with Python 2.7. I am trying to use a base.html template that can be used globaly through out the entire site, where every app and access it. Here is my test site's current structure:
twms
polls
migrations
static
templates
project
migrations
static
templates
project
index.html
tmws
static
templates
tmws
base.html
Here is the code for project/templates/project/index.html
{% extends 'tmws/base.html' %}
{% block content %}
<h1>Projects</h1>
<ul>
{% for project in project_list %}
<li>{{ project.name }}</li>
{% endfor %}
</ul>
end of list
{% endblock %}
This is the error I am receiving:
TemplateDoesNotExist at /project/
tmws/base.html
How do I access tmws/tmws/templates/tmws/base.html from any of my apps?
Any help would be greatly appreciated!
Let me know if any additional information is needed.
EDIT
Here are my template settings from settings.py:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, 'templates'), # If i leave both or just comment one one out I still get the same error
'tmws.tmws.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',
],
},
},
]
I think you might be having a problem with your template directory configuration. In your project´s settings.py try to check if you have a configuration similar to this one:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'your template dir name')]
,
'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',
],
},
},
]
Where 'your template dir name' should be tmws. This will make django search for this directory whenever you try to extend templates in your HTML. You can add as many directories as you want.
I think right now Django must be searching for the template in:
twms/project/templates/project
So maybe if you place your base.html file there Django will be able to find it.
Another suggestion would be to create a general templates directory and place your base.html there since you want it to be used in the entire site. This is just my taste for ordering templates, but it should work either way.
Edit:
Adding the following in settings.py solved the problem. Read comments for more info:
MASTER_BASE_DIR = os.path.dirname(__file__)
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(MASTER_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',
],
},
},
]
Check the TEMPLATES value in your settings. You can add the DIR option with a directory where you can put all your common templates.
Link: https://docs.djangoproject.com/en/1.9/ref/settings/#templates
You need to add all templates folders to the TEMPLATES settings in settings.py. Django will then treat them as if they're all in the same folder. It seems like you have not added all of them. You want your TEMPLATES to look something like this:
TEMPLATES = [
{
'DIRS': [
'twms.tmws.templates', # Since this is not in an app
],
'APP_DIRS': True, # Automatically include the templates from INSTALLED_APPS
},
]
You set up the directories to search for the templates as follows:
'DIRS': [os.path.join(MASTER_BASE_DIR, 'templates'),]
where it should read instead:
'DIRS': [os.path.join(MASTER_BASE_DIR, 'tmws/templates'),]
Why? because BASE_DIR is defined as follows:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# -> os.path.dirname(os.path.dirname(/your/path/tmws/tmws/settings.py))
# -> /your/path/tmws/
So BASE_DIR points to your top folder, if you then join it with 'templates', it becomes: /your/path/tmws/templates, which doesn't exist. However, with the changed line in the DIRS list, it will become /your/path/tmws/tmws/templates which is the correct one.

Categories

Resources