problem with images on a custom 404 page, django - django

I am trying to make custom 404 page by adding an image to the page. Problem is that image is not displaying on a page. This image is accessible from any other page in each app in DEBUG TRUE or FALSE mode, no difference, except 404 page where it represented as a just an empty frame.
Image is placed in app/static/app root. Tried to place it is main static root -no difference.
# urls.py
handler403 = curry(permission_denied, exception=Exception('Permission Denied'),
template_name='errors/403.html')
handler404 = curry(page_not_found, exception=Exception('Page not Found'),
template_name='errors/404.html')
handler 403 and handler 404 works fine, except images failure.
# template
<!-- templates/errors/404.html -->
{% extends "base.html" %}
{% block title %} error 404 {% endblock %}
{% load static %}
{% block content %}
<img src="{% static "appname/404.png" %}" alt="404">
{% endblock content %}
Problem is only on 404/403 pages. Everywhere else -no problems at all. Text itself displays normally.
Question is what should I check in terms of possible pitfalls I possible keeping out of scope ?
thanks in advance
p.s. tried
<img src="{% get_static_prefix %}404.png" >
still no effect

Solution is to run server in the following mode:
manage.py runserver --insecure

Related

Find if static file exists before calling in deployment - Django

In production I am able to run:
#views.py
from django.contrib.staticfiles import finders
result = finders.find(f'Images/{var}')
context = {"r", results}
#template.html
{% if r %}
{% with 'Images/'|add:var as var %}
<img src="{% static var %}">
{% endwith %}
{% endif %}
However, now that my files are being stored in Google's buckets finders.find(f'Images/{var}') keeps returning False and my images aren't being displayed. I need a way to test if files exists prior to calling them to avoid displaying empty boxes when a variable's image does not exist.
Incase there's a way to search through the remote buckets, here is my settings.py configuration:
#settings.py
. . .
STATIC_URL = http://storage.googleapis.com/env("BUCKET")/static/
STATIC_ROOT = http://storage.googleapis.com/env("BUCKET")/static/
you could use request lib:
import request
r = requests.head(file_url)
if r.status_code == 200:
do something...
but that's gonna cost you a lot (I mean response time, not money)
better solution would be using JS, something like this (this is jquery):
<script>
$("img").on("error", function () {
//$(this).attr("src", "broken.gif"); // set default pic
$(this).hide(); // hide img
});
</script>
That way you can hide or change all images in the page, when it doesn't load
After looking through a bunch of websites (mostly SO,) I found this solution really helpful:
{% with 'Images/'|add:var as var %}
<img src="{% static var %}" class="img" onerror="this.onerror=null;this.style.display='none';src='';this.class='';" />
{% endwith %}

Django custom 404 page not recognized

I've placed a custom 404.html page in my root templates directory, but whenever an invalid URL is requested, the default error page is given. Strangely in production, "Internal Server Error" is displayed, while "Not Found.
The requested resource was not found on this server." is displayed on localhost.
Debug is set to false in both cases.
app/templates/app/404.html:
{% extends "app/base.html" %}
{% block page_header %}
<h1>404</h1>
<h2>The page you requested is not available.</h2>
<i class="far fa-meh"></i>
{% endblock page_header %}
I had to create a new templates folder in the root (not in an app folder) without any sub-folders. The file is located now in root/templates/404.html

Using an embedded Iframe in Django?

How do I use an Iframe in Django. Currently its searching for the src url in my own files. How do I tell it to not look in my files but to look at the url?
Currently I'm storing the embed code minus the tag in a database and then trying to dynamically generate it in my template.
games.embed = 'allowtransparency="true" width="485" height="402" src="//scratch.mit.edu/projects/embed/82384372/?autostart=false" frameborder="0" allowfullscreen'
{% extends 'code_games/base.html' %}
{% block content %}
<div class="game">
{{games.title|linebreaks}}
<iframe '{{ games.embed }}'></iframe>
</div>
{% endblock %}
The iframe itself shows up on my page but the contents of it don't.
The request URL per the error:
Request URL: http://chacemcguyer.pythonanywhere.com/games/1/%22/scratch.mit.edu/projects/embed/82384372/?autostart=false%22
You can see that its searching for the url in my site. How do I get around that?
The error also says:
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
Then it shows all of my urls from settings.py
I found a solution!
What I had to do was make sure that the iframe content which was coming from my database was |safe
I changed:
<iframe src='{{ games.embed }}'></iframe>
to
<iframe src='{{ games.embed|safe }}'></iframe>

loading an image using the static tag from a static path

I am unable to load an image on my index page using the following syntax
{% extends "base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<-!---This is the statement-->
<-div data-src= "{% static "bootstrap/images/slider/slider-img1.jpg" %}">
<-/div>
{% endblock content %}
I added an extra - (dash) in the div because the post had difficulty displaying it.
Anyways I am getting the error
Invalid block tag on line 69: 'static', expected 'endblock'. Did you forget to register or load this tag?
I think this is a directory structure. My directory currently looks like this
|_mainApp
| |_______index.html ------>This is where i am trying to run the statement
|_templates
| |_______base.html ------->The statement works fine in the base
|_static
|_bootstrap
|_CenterApp
|_settings.py
|_urls.py
Any suggestions on why I am getting that error is that a location issue and the content cant be found ? or is it something else ?
use
{% load staticfiles %}
below you have extended your base.html
In django template it is important to call {% load staticfiles %} whenever you are using static in template. More details here
Whenever you use {% extend "some_page.html" %} and you need some links with static url you can use {{STATIC_URL}} instead of {% static "/some/link/" %}
So in your case, use it as:
<-div data-src= "{{STATIC_URL}}bootstrap/images/slider/slider-img1.jpg">

include static files from django template

I'm trying to include a static html page from a django template.
I tried using {% include the_static.html %} but this doesn't work for some unknown reason.
the_static.html page is a data page that will be modified often with an html editor.
and my_model has a url to this html and include it. But django refuses to find it although I'm sure I've setup the path correctly.
You can write your custom template tag to do this.
Create a file named includestatic.py under appname/templatetags/. Also, remember to create appname/templatetags/__init__.py, to include the app in settings and to restart the server.
includestatic.py should have this code:
from django import template
from django.contrib.staticfiles import finders
from django.utils.html import escape
register = template.Library()
#register.simple_tag
def includestatic(path, encoding='UTF-8'):
file_path = finders.find(path)
with open(file_path, "r", encoding=encoding) as f:
string = f.read()
return escape(string)
To use it in your template, put {% load includestatic %} at the top of your template, and then use the tag like {% includestatic "app/file.txt" %}.
I am not sure I understand everything yet...
You've an HTML page served by Django on a given url, let's suppose it to be http://mydjangodomain/get_the_static/. This URL is set in the urls.py of your model. Ok, that's normal.
You have a django template for this model. Let's suppose it's defined in a template directory mytemplates/mymodeltemplates/ and it's called myfrontpage.html (since in Django templates are html files).
I guess you've an URL defined in your urls.py to server that front page ? Let's suppose it's http://mydjangodomain/get_the_front_page/
Now I don't understand how your front page use your static html. Do your final front page html need the static's URL for a "src" attribute or something like it, or do you need to include the static's html into the front page's html ?
In the 1st case, you already have the URL, it's http://mydjangodomain/get_the_static/ so just use it as if.
In the 2nd case, you don't need the previous URL, get ride of it. Furthermore, put the_static.html in mytemplates/mymodeltemplates/. Then you need the {% include "/mymodeltemplates/the_static.html" %} tag. If this doesn't work, make sure you've the following in your settings:
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
APPLI_ROOT_PATH = "<absolute_path_to_the_application_root_on_your_server>"
TEMPLATE_DIRS = (
'%s/mytemplates' % APPLI_ROOT_PATH,
)
Sort of resurrecting the dead, but at least with django 1.10, there's a very clean answer here:
http://www.effectivedjango.com/tutorial/static.html
an excerpt from that page:
Simple Template Inclusion We want to add the Boostrap CSS to all of
our templates, but we’d like to avoid repeating ourself: if we add it
to each template individually, when we want to make changes (for
example, to add another stylesheet) we have to make them to all the
files. To solve this, we’ll create a base template that the others
will inherit from.
Let’s create base.html in the templates directory of our contacts app.
{% load staticfiles %}
<html>
<head>
<link href="{% static 'bootstrap/css/bootstrap.min.css' %}"
rel="stylesheet" media="screen">
</head>
<body>
{% block content %}
{% endblock %}
<script src="{% static 'bootstrap/js/bootstrap.min.js' %}"></script>
</body>
</html>
base.html defines the common structure for our pages, and includes a
block tag, which other templates can fill in.
We’ll update contact_list.html to extend from base.html and fill in
the content block.
{% extends "base.html" %}
{% block content %}
<h1>Contacts</h1>
<ul>
{% for contact in object_list %}
<li class="contact">{{ contact }}</li>
{% endfor %}
</ul>
add contact
{% endblock %}
Having followed this exactly, I now have a base.html that includes all my style references and the navigation bars/etc, so the html in the block content is merely the central contents of each (varying) page.
Do you mean that you want to EXTENDS the parent template the_static.html?
If yes, you should add below code at the first line of your children template:
{% extends "the_static.html" %}
Details documentation can be found here