How to refer to static files in my css files? - django

I have a reference inside my CSS file that refers to a static image:
#logo
{
background: url('/static/logo.png')
}
This works just fine on my dev machine but not on my production environment since the url should be static.mydomain.com/logo.png.
How do I dynamically change the css file according to the STATIC_URL in my settings file?

Use a relative path. Relative to the folder where the css file reside

You can move any CSS that contains static file paths to inline CSS, contained in the template.
i.e.
<div style="background: url('{% static 'logo.png' %}')"></div>
The catch here is that it won't work for #media queries, you'd need to put those in a block, e.g.
<style>
#media (min-width: 1200px){
background: url('{% static 'logo.png' %}');
}
</style>

Use absolute URL from base directory, this will point to any file in a static folder within an app
settings.py:
STATIC_URL = '/static/'
style.css:
background-image: url('/static/img/sample.jpg');

If you want to use {% static %} tag in your CSS file, you should use {% include %} tag. Here is an example to do so:
foo.html
{% load static %}
{% load i18n %}
{% load widget_tweaks %}
<!DOCTYPE html>
<html>
<head>
<style>
{% include "path/to/custom_styles_1.css" %}
</style>
<link rel="stylesheet" href="{% static 'css/custom_styles_2.css' %}">
</head>
<body>
<!-- Your HTML body -->
</body>
</html>
custom_styles_1.css
{% load static%}
{
background: url('{% static "/img/logo.png" %}')
}
custom_styles_2.css
.fa {
position: relative;
text-align: center;
font-family: BTitrBold;
font-size: 3.5em;
}
.name {
position: absolute;
top: 37%;
right: 15%;
}
.school {
position: absolute;
top: 530px;
right: 200px;
}
.id {
position: absolute;
top: 700px;
right: 200px;
}
.degree {
position: absolute;
top: 740px;
left: 195px;
}
custom_styles_1.css is the CSS file that includes {% static %} tag. You should integrate it with your foo.html file with {% include %} tag. In this way, Django will put all the styles you need at the appropriate place and render the static tags correctly.
custom_styles_2.css is a normal CSS file located in STATIC_ROOT directory, so you can use {% static %} tag for it without any problem.

See this similar stackoverflow question.
The only way to do what you want is to generate your CSS through Django. HTML is usually associated with Django views and templates, but in truth, you can return any file type: CSS, JavaScript, plain text, etc. However, doing so will add overhead to your site, so setting proper HTTP headers and server-side caching of the generated file will be very important.
Basic method:
return render_to_response('stylesheet.css',
{ 'domain': 'http://static.mydomain.com/' },
context_instance=RequestContext(request),
mimetype='text/css'
)
Alternatively, you can set up hosts on your system that map the static domains back to localhost for development purposes. Then, you can reference the domain as normal, but it'll still pull from your development files. Also, if you happen to have Ruby installed on your system, you can make use of a rubygem called Ghost. It lets you easily create, enable, disable, and delete custom hosts right from the command-line with no fuss.

If you're using django-libsass to generate your css, you can use custom functions to bridge django and the sass precompiler.
As a matter of fact, the function static is already implemented, and you can use it:
.foo {
background: url(static("myapp/image/bar.png"));
}
as described here:
https://github.com/torchbox/django-libsass#custom-functions

There might be a way to get django to treat the CSS file like a template (I'm not very familiar with django) but you might want to try a different solution instead: use a dynamic stylesheet language such as LESS or Sass. With LESS it would be as simple as
#base: "//static.example.com/"
#logo {
background: url(%("%s/logo.png", #base))
}

Okay, 10 years down the line and I am facing this now. Here is my fix which will save you some trouble.
PS Not really sure if it is ethical however
grab your CSS file and place it in Templates
In your html file,
<style>
{% include 'path/to/css' %}
</style>
Solved my problems.

If your images aren't too big you can use data URIs, which can be embedded right in the css file without any links. They look like this:
.box-with-background {
background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgI=')
background-repeat: repeat;
}
Usually they're a bit longer then the one I've shown. You can generate them with javascript and you can find some online generators.

Related

Disable prefers-color-scheme: dark in django admin

I have dark mode enabled on Mac, but it looks awkward in django admin panel with ckeditor. Is it any option to disable it in Chrome or Django admin? I have already tried themes and browser extensions with no success.
It looks like you're using some 3rd party theme for Django admin. I suggest checking if the maintainer of this theme wants to support Django 3.2 any time soon.
As for the quick fix for that, you can introduce your own stylesheet that will reset variables responsible for the dark theme. You can find the variables here.
To achieve that, create a separate css file in your static file directory, copy over the #media declaration from the code fragment mentioned above and paste the normal color scheme inside it (also to be found in the same code fragment). After that, create a admin/base_site.html template, fill it with this content or the equivalent from the theme you're using and link your custom CSS in the extrastyle block (you may need to create that block by hand).
There's an app for that.
pip install django-light, details at https://github.com/frnhr/django-light.
Full disclosure: I'm the author. Well, more like "packager", not much original code there...
as #GwynBleidD wrote, I changed my admin/base_site.html like this, and it works:
{% extends "admin/base_site.html" %}
{% block extrastyle %}
<style>
#media (prefers-color-scheme: dark) {
:root {
--primary: #79aec8;
--primary-fg: #fff;
--body-fg: #333;
--body-bg: #fff;
--body-quiet-color: #666;
--body-loud-color: #000;
--breadcrumbs-fg: #c4dce8;
--breadcrumbs-bg: var(--primary);
--link-fg: #447e9b;
--link-hover-color: #036;
--link-selected-fg: #5b80b2;
--hairline-color: #e8e8e8;
--border-color: #ccc;
--error-fg: #ba2121;
--message-success-bg: #dfd;
--message-warning-bg: #ffc;
--message-error-bg: #ffefef;
--darkened-bg: #f8f8f8; /* A bit darker than --body-bg */
--selected-bg: #e4e4e4; /* E.g. selected table cells */
--selected-row: #ffc;
--close-button-bg: #888; /* Previously #bbb, contrast 1.92 */
--close-button-hover-bg: #747474;
}
}
</style>
{% endblock %}
You can disable dark mode in Django 4.1 and above by overriding admin/base.html in your template. https://github.com/django/django/pull/14929
{% extends "admin/base.html" %}
{% block dark-mode-vars %}{% endblock %}

How to let static CSS files access other files such as .eot, .ttf, .woff, etc... on Django

When I try to access styles.css, Django loads styles.css but not the files that it loads for itself.
{% load static %}
<link rel="stylesheet" href="{% static 'frontpage/css/style.css' %}">
here is the part of styles.css that I suspect is causing the problem
src: url("../fonts/icomoon/icomoon.eot?srf3rx");
src: url("../fonts/icomoon/icomoon.eot?srf3rx#iefix") format("embedded-opentype"), url("../fonts/icomoon/icomoon.ttf?srf3rx") format("truetype"), url("../fonts/icomoon/icomoon.woff?srf3rx") format("woff"), url("../fonts/icomoon/icomoon.svg?srf3rx#icomoon") format("svg");
It seems that the css file is unable to access the .eot files, but I have no way of knowing because django is showing everything as running smoothly.
I had the same issue and spent a little time searching how to solve it... Follow below what solved this issue for me:
You have to be sure your .ttf file is within any of the STATIC_ROOT paths...
eg.:
(eg.: {% static 'fonts/yourfontname.ttf'%}
In your .css file, create the #font-face parameters as show below:
eg.:
#font-face { font-family: yourfontname; src:
url("../fonts/yourfontname.ttf"); }
VERY IMPORTANT: the font-family name has to be WITHOUT quotes! Most of the people do this mistake.
Also, in the url path, I used .. because my fonts folder is one folder back from my .css file. So this path depends on your structure. I just want to mention that static do not work in css file, instead you have to consider the path from the .css file you are editing.
Now you just normally include the font name where you need it within the .css file. But at this time WITH quotes!!! eg.:
.logotext { font-family: 'yourfontname'; margin-left: 130px;
font-size: 40px; etc...}

django-admin-tools how to change the "logo" on login

I managed to change the menus and dashboard, but how to change the "logo" (Word Django) on login and admin page?
See image:
django-admin-tools Login
Duplicate this file saving the same structure — https://github.com/django-admin-tools/django-admin-tools/blob/master/admin_tools/theming/templates/admin/base.html
Then after {% render_theming_css %} add:
<style type="text/css">
#header #branding h1 {
background-image: url("../path/to/your/image.png");
}
</style>
Here's the docs on how to overload templates — https://docs.djangoproject.com/en/dev/ref/contrib/admin/#overriding-vs-replacing-an-admin-template

flask jinja2 insert content of css file inline

I have a flask project in which one of the pages needs to be self contained.
I have a separate file whose content I need to insert into the html page's head.
What's the easiest way to do it?
Simply use the include statement to include the contents:
<style type="text/css">
{% include "your.css" %}
</style>

Generate barcodes in Django site

I want to add barcode generation in a Django site and wonder what the best library or api would be. My first preference is something callable from Python - either written in Python or a C/C++ lib that I can wrap with ctypes/SWIG. Otherwise I can call out to the command line if must be.
I need at least EAN and UPC symbologies.
I've tried pybarcode but the image quality is too low. And Elaphe looks promising but from the Python interpreter all I could make was a QR Code -- EAN and UPC errored out (maybe because the syntax/usage was unclear from the documentation).
Use pybarcode and generate the barcode as SVG: http://packages.python.org/pyBarcode/barcode.html#creating-barcodes-as-svg
No problem of image quality in that case.
This thread is quite old, but in case anyone else is looking for an answer to this... code39 is a font, as are most types of barcode. You can simply use google fonts:
https://fonts.google.com/specimen/Libre+Barcode+39+Extended+Text?selection.family=Libre+Barcode+39+Extended+Text
Aside from that option, you could host static files, one solution could be this project on github:
https://github.com/Holger-Will/code-39-font
In that project all you need are the files associated with the size you want, and the code39_all.css file. The rest you could delete, if you like.
For your reference, I'm using both here:
{% load staticfiles %}
{% load static %}
<html>
<head>
<link href="https://fonts.googleapis.com/css?family=Libre+Barcode+39+Extended+Text" rel="stylesheet">
<link rel="stylesheet" href="{% static 'code-39-font-master/code39_all.css' %}"/>
</head>
<body>
<style>
body {
font-family: 'Libre Barcode 39 Extended Text', cursive;
font-size: 48px;
}
</style>
<div>I'm just a code39 google font</div>
<div><class="code_39_S">I'm generated with static files!</div>
</body>
</html>
reportlab could be a good alternative to pybarcode, especially when using some of its other features.
There is a howto for barcodes in Django with reportlab, works well for me.
https://code.djangoproject.com/wiki/Barcodes