django- how to address static files in 404.html template - django

according to django's documentation:
When you raise Http404 from within a view, Django loads a special view devoted to handling 404 errors. By default, it’s the view django.views.defaults.page_not_found(), which either produces a very simple “Not Found” message or loads and renders the template 404.html if you created it in your root template directory.
, i created a 404.html file in the root template directory.
when the app raises a 404 error, this 404.html that i created before, will shown, but it's css and it's background image not load.
this is the 404.html file code:
<!DOCTYPE html>{% load staticfiles %}
<html>
<head>
<title>not found</title>
<link rel="stylesheet" href="{% static 'css/error_style.css' %}"/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"/>
</head>
<body class="color-404">
<div id="error">
<img class="error-image" src="{% static 'img/404.jpg' %}"/>
</div>
<div class="error-router">
<i class="fa fa-home"></i>
<i class="fa fa-arrow-left"></i>
</div>
</body>
</html>
how can i fix this problem?
tanx

Not really an answer to your question, but in general it is best to not have external .js and .css files in error-pages.
Include it in the page itself, to avoid situations like this, where for some reason the error-page produces an error. Use a single static page.

I found what was the problem.
because i set DEBUG to False, django's built-in webserver, was not served staticfiles.

Related

I had an html comment in a Django template, and it was causing a server error when DEBUG=False, why?

Previously I had a favicon.png, I deleted the favicon.png file. This did not create any issues until I switched from DEBUG = True to DEBUG = False in my settings.py file. And I got a 500 server error.
To diagnose the issue I added DEBUG_PROPAGATE_EXCEPTIONS = True to my settings.py
And I got the following error:
raise ValueError("Missing staticfiles manifest entry for '%s'" % clean_name)
ValueError: Missing staticfiles manifest entry for 'favicon.png'
Only place where there was even a mention of 'favicon.png' was as an html comment in my login html template file, login.html contained the following in head:
<title>Login</title>
<!-- <link rel="shortcut icon" type="image/png" href="{% static 'favicon.png' %}"/> -->
when I deleted the favicon.png html comment so that code became:
<title>Login</title>
I no longer got a 500 server error, and things worked again.
How can an html comment cause an error in my code? I thought it was impossible for an html comment to cause an error.
The line:
<!-- <link rel="shortcut icon" type="image/png" href="{% static 'favicon.png' %}"/> -->
will be commented out when the page is rendered, but when the html template is constructed, Django will still try to execute {% static 'favicon.png' %} because template languages don't understand html, which includes, but is not limited to, html comments.
Template languages need to decide what special characters it will use, and it can't use special html characters, because it wouldn't be able to distinguish between what is html code, and what is template code.
So in the case of django, <! is not a "special symbol" in the template language, so it is ignored, while {% is a "special symbol", so code within that block will be executed.
If you want to comment this out, you can do either of the following:
{% comment %}
<link rel="shortcut icon" type="image/png" href="{% static 'favicon.png' %}"/>
{% endcomment %}
{% # <link rel="shortcut icon" type="image/png" href="{% static 'favicon.png' %}"/> %}
Edit
Here is a snippet from the docs that is related to your issue:
In addition to these configuration steps, you’ll also need to actually serve the static files.
During development, if you use django.contrib.staticfiles, this will be done automatically by runserver when DEBUG is set to True (see django.contrib.staticfiles.views.serve()).
This method is grossly inefficient and probably insecure, so it is unsuitable for production.
See Deploying static files for proper strategies to serve static files in production environments
This leads me to suspect that your settings.py is not properly configured for deployment.

Django + React production setup

It looks like a very basic question and I'm confused by the fact that I cannot find any sensible tutorial on that. I'm trying to setup Django + React production build. After running all kinds of transpilation, minification etc. I end up having .js and .css bundles, index.html and several other files like favicon, service-worker.js etc. Now I need to serve this with Django.
All of these files are static files and should probably be served as static files by the http server (nginx in my case). The variant I came up with was to modify index.html to make it a valid Django template: {% load static %} in the beginning, replace all hardcoded links with {% static 'filepath' %} and serve it using TemplateView, other files are served by nginx. This works fine, however, modifying build results looks like a bad idea. Generated bundles contain a unique hash for each build and I would need to replace that hash in the template after each build. I obviously can automate it but it looks weird. I would prefer not to touch build results at all, but how should I serve static files then? nginx is configured to serve static files under /static/ path and cannot serve files like service-worker.js as static files.
So the question is how do I configure Django + React for production so that I don't have to manually modify build results and can serve static files properly using nginx?
The main problem to combine React and Django is that Django wants to render the templates by itself, but React wants also to execute the render, since it has been created for that. That's why there a lot of approximations that use django just as as REST API when working with react.
But, if you want django to Render the templates to avoid having a Single Page Application (as react provides) and to use all the other tools from django, the main flow that we use in our company is:
You create your components, in js files. For example: component.js
You use babel to compile the JSX files to native Javascript, and babels creates, for example, component.build.js. Django will serve this compiled files, so react is going to be used only in develop tasks because all React code will be transformed to JS before moving to production. For django, all the react components will be just JS code already compiled.
You can use Webpack to automatically move component.build.js to a folder where django can serve them, for example your_project/static/your_app/component.buid.js
You create a django template base.html which will be used as the base template that all your templates will extend. Here you put the header and all your common scripts and styles. For example, bootstrap should be here if used. Remember to leave blocks in this base template to use them in the templates that are going to extend the base.html. Here is the base.html that we use:
{% with version="2.0" %}
<!DOCTYPE html>
{% load static %}
<html>
<head>
<meta charset="utf-8">
<title></title>
<meta name="author" content="">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- base styles goes here -->
<!-- include here bootstrap or styles that are common to all your website -->
<link rel="shortcut icon" type="image/png" href="{% static 'favicon.ico' %}"/>
<!-- custom styles for each app go into this block-->
{% block app_styles %}
<!-- here will go the apps local styles -->
{% endblock %}
</head>
<body>
{% block app %}
<!-- This block will be used by the apps to load their react components -->
{% endblock %}
<!-- base js go here -->
<script src="{% static 'common/pluggins/jquery3.4.1.min.js' %}"></script>
</script>
<script src="{% static 'common/pluggins/fontawesome.js' %}"></script>
<script src="{% static 'common/scripts/base.js' %}?v={{version}}"></script> <!-- File for common utils -->
<!-- custom js for each app go here. You should define your Content() here -->
{% block local_scripts %}
<!-- here will go the app local scripts -->
{% endblock %}
</body>
</html>
{% endwith %}
Create the templates for each of your django apps, by extending the base.html. Remember to include here the <div> that is going to be used by react to render the content. Aslo, remember that this is the place to include the component.build.js compiled JS file that bable created before. Here there is an example that we use to build a dashboard.html in our website:
{% extends 'common/base.html' %}
{% load static %}
{% block app_styles %}
<link rel="stylesheet" href="{% static 'dashboard/styles/dashboard.css' %}?v={{version}}">
{% endblock %}
{% block app %}
<!-- Here is the div used by react -->
<div id="myreact-content"></div>
{% endblock %}
{% block local_scripts %}
<!-- IMPORTANT: Import here the compiled file -->
<script src="{% static 'component.build.js' %}"></script>
{% endblock %}
Set the correct urls.py in your projects and in your app
Set the correct configuration in setting.py to make accesible the static js/css files and the templates
Run your django server and You're done!
In this video you have a small guide on how to configure npm, babel and django. With a correct configuration, everything will be updated automatically when you change some code in your JSX (not compiled) files, so the develop tasks will be more friendly.
https://www.youtube.com/watch?v=Mx3ChaYA0Gw

Having confusion with pathing in Django templates

When I use the url(r'^consultar/$', 'rcb.core.views.consultar'), in browser http://localhost:8000/consultar the consultar.html file find the jquery-1.11.2.min.js file, appearing the following information:
Remote Address:127.0.0.1:8000
Request URL:http://localhost:8000/static/js/jquery-1.11.2.min.js
Request Method:GET
Status Code:200 OK
But when I use the url(r'^proposta/consultar/$', 'rcb.core.views.consultar'), in browser http://localhost:8000/proposta/consultar/ the consultar.html file not find the jquery-1.11.2.min file.js. Appearing the following error:
Remote Address:127.0.0.1:8000
Request URL:http://localhost:8000/proposta/static/js/jquery-1.11.2.min.js
Request Method:GET
Status Code:404 NOT FOUND
Could someone help me fix the code to run the url http://localhost:8000/proposta/consultar/
Below is the code and the structure of files and directories:
consultar.html
{% extends 'base.html' %}
....
base.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="../static/js/jquery-1.11.2.min.js" type="text/javascript"></script>
</head>
<body>
{% block corpo %}{% endblock %}
</body>
</html>
views.py
def consultar(request):
propostas_salvas=search()
return render_to_response('consultar.html', { 'propostas_salvas' : propostas_salvas}, context_instance=RequestContext(request))
My structure of files and directories is:
rcb (Project)
core (is the App)
static
js
jquery-1.11.2.min.js
template
base.html
consultar.html
views.py
...
...
...
You should use path to javascript relative to your domain, not to document you're requesting, because for each document relative path to javascript would be different. So change that line:
<script src="../static/js/jquery-1.11.2.min.js" type="text/javascript"></script>
into:
<script src="/static/js/jquery-1.11.2.min.js" type="text/javascript"></script>
Or even better, load static in your template and use static file management built into django:
<script src="{% static "js/jquery-1.11.2.min.js" %}" type="text/javascript"></script>
That way you can change later your STATIC_URL in settings and django will correct path to your static files. Even if they are on different domain (some CDN or no-cookie domain just for your static files).

How can I get a favicon to show up in my django app?

I just want to drop the favicon.ico in my staticfiles directory and then have it show up in my app.
How can I accomplish this?
I have placed the favicon.ico file in my staticfiles directory, but it doesn't show up and I see this in my log:
127.0.0.1 - - [21/Feb/2014 10:10:53] "GET /favicon.ico HTTP/1.1" 404 -
If I go to http://localhost:8000/static/favicon.ico, I can see the favicon.
If you have a base or header template that's included everywhere why not include the favicon there with basic HTML?
<link rel="shortcut icon" type="image/png" href="{% static 'favicon.ico' %}"/>
One lightweight trick is to make a redirect in your urls.py file, e.g. add a view like so:
from django.views.generic.base import RedirectView
favicon_view = RedirectView.as_view(url='/static/favicon.ico', permanent=True)
urlpatterns = [
...
re_path(r'^favicon\.ico$', favicon_view),
...
]
This works well as an easy trick for getting favicons working when you don't really have other static content to host.
In template file
{% load static %}
Then within <head> tag
<link rel="shortcut icon" href="{% static 'favicon.ico' %}">
This assumes that you have static files configured appropiately in settings.py.
Note: older versions of Django use load staticfiles, not load static.
Universal solution
You can get the favicon showing up in Django the same way you can do in any other framework: just use pure HTML.
Add the following code to the header of your HTML template.
Better, to your base HTML template if the favicon is the same across your application.
<link rel="shortcut icon" href="{% static 'favicon/favicon.png' %}"/>
The previous code assumes:
You have a folder named 'favicon' in your static folder
The favicon file has the name 'favicon.png'
You have properly set the setting variable STATIC_URL
You can find useful information about file format support and how to use favicons in this article of Wikipedia https://en.wikipedia.org/wiki/Favicon.
I can recommend use .png for universal browser compatibility.
EDIT:
As posted in one comment,
"Don't forget to add {% load staticfiles %} in top of your template file!"
In your settings.py add a root staticfiles directory:
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
Create /static/images/favicon.ico
Add the favicon to your template(base.html):
{% load static %}
<link rel="shortcut icon" type="image/png" href="{% static 'images/favicon.ico' %}"/>
And create a url redirect in urls.py because browsers look for a favicon in /favicon.ico
from django.contrib.staticfiles.storage import staticfiles_storage
from django.views.generic.base import RedirectView
urlpatterns = [
...
path('favicon.ico', RedirectView.as_view(url=staticfiles_storage.url('images/favicon.ico')))
]
<link rel="shortcut icon" href="{% static 'favicon/favicon.ico' %}"/>
Just add that in ur base file like first answer but ico extension and add it to the static folder
First
Upload your favicon.ico to your app static path, or the path you configured by STATICFILES_DIRS in settings.py
Second
In app base template file:
{% load static %}
<link rel="shortcut icon" type="image/png" href="{% static 'favicon.ico' %}"/>
You can make apps use different favicon.ico files here.
Addition
In project/urls.py
from django.templatetags.static import static # Not from django.conf.urls.static
from django.views.generic.base import RedirectView
Add this path to your urlpatterns base location
path('favicon.ico', RedirectView.as_view(url=static('favicon.ico'))),
This can let installed app(like admin, which you should not change the templates) and the app you forget modify the templates , also show a default favicon.ico
if you have permission then
Alias /favicon.ico /var/www/aktel/workspace1/PyBot/PyBot/static/favicon.ico
add alias to your virtual host. (in apache config file ) similarly for robots.txt
Alias /robots.txt /var/www/---your path ---/PyBot/robots.txt
I tried the following settings in django 2.1.1
base.html
<head>
{% load static %}
<link rel="shortcut icon" type="image/png" href="{% static 'images/favicon.ico' %}"/>
</head>
settings.py
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'` <br>`.............
Project directory structure
view live here
<link rel="shortcut icon" type="image/png" href="{% static 'favicon/sample.png' %}" />
Also run: python manage.py collectstatic
The best solution is to override the Django base.html template. Make another base.html template under admin directory. Make an admin directory first if it does not exist. app/admin/base.html.
Add {% block extrahead %} to the overriding template.
{% extends 'admin/base.html' %}
{% load staticfiles %}
{% block javascripts %}
{{ block.super }}
<script type="text/javascript" src="{% static 'app/js/action.js' %}"></script>
{% endblock %}
{% block extrahead %}
<link rel="shortcut icon" href="{% static 'app/img/favicon.ico' %}" />
{% endblock %}
{% block stylesheets %}
{{ block.super }}
{% endblock %}
Came across this while looking for help. I was trying to implement the favicon in my Django project and it was not showing -- wanted to add to the conversation.
While trying to implement the favicon in my Django project I renamed the 'favicon.ico' file to 'my_filename.ico' –– the image would not show. After renaming to 'favicon.ico' resolved the issue and graphic displayed. below is the code that resolved my issue:
<link rel="shortcut icon" type="image/png" href="{% static 'img/favicon.ico' %}" />
Best practices :
Contrary to what you may think, the favicon can be of any size and of any image type. Follow this link for details.
Not putting a link to your favicon can slow down the page load.
In a django project, suppose the path to your favicon is :
myapp/static/icons/favicon.png
in your django templates (preferably in the base template), add this line to head of the page :
<link rel="shortcut icon" href="{% static 'icons/favicon.png' %}">
Note :
We suppose, the static settings are well configured in settings.py.
Just copy your favicon on:
/yourappname/mainapp(ex:core)/static/mainapp(ex:core)/img
Then go to your mainapp template(ex:base.html)
and just copy this, after {% load static %} because you must load first the statics.
<link href="{% static 'core/img/favi_x.png' %}" rel="shortcut icon" type="image/png" />
Now(in 2020),
You could add a base tag in html file.
<head>
<base href="https://www.example.com/static/">
</head>
Sometimes restarting the server helps.
Stop the server and then rerun the command: python manage.py runserver
Now your CSS file should be loaded.

Django template img src not working

I want to print an image by using a img src tag in a Django template file "base.html":
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
<title>Foto</title>
</head>
<body>
<h1>My helpful timestamp site</h1>
<img src="google.png" / >
<hr>
<p>Made by ... </p>
</body>
</html>
In views.py I define:
def hello(request):
return render_to_response('base.html')
But the image does not show up in the browser. If I open it as a simple html file, it shows up in the browser.
In recent versions of django
<img src="{% static 'path/to/image.ext' %}"/>
That happens because Django does not know the path to this image.
Make a folder named static/, and then a folder named images/ in your project root(where your settings.py file resides).
my_project/
my_project/
settings.py
static/
images/
google.png
And then change it to:
<img src="{{STATIC_URL}}images/google.png" / >
More here.
You have got to add load static tag in the beginning of your Django template, best luck with below code.
{% load static %}
<img src="{% static 'path/to/image.ext' %}"/>