i can not show the images in html - python

I´m new in python and django.
My code is below and the problem is that the images do not appear.
I include in the teste.html this tag but it didn´t work src="./assets/images/3ed274bc061c771ef0b153111a6fe932_logocartorio.png"
My path is:
BCcartorio
bccartorio
settings
urls
iddigital
views
urls
templates
iddigital
teste.html
assets
css
images
js
My iddigital.views.py:
from django.shortcuts import render, HttpResponse
def home(request):
return (render(request, "iddigital/teste.html"))
My teste.html:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>teste</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</head>
<body>
<h1>Welcome</h1>
<button class="btn btn-danger" type="button" name="button">login</button>
<div class="bd-vertical-align-wrapper">
<img class="bd-imagelink-1 bd-own-margins bd-imagestyles " src="./assets/images/3ed274bc061c771ef0b153111a6fe932_logocartorio.png">
</div>
</body>
</html>

It is not a good practice to hard-code the URL of an image as this can cause many unexpected problems(e.g. paths mixup). In order to avoid this Django provides a hassle-free way to manage and serve your static files easily.
First you have to include the django.contrib.staticfiles app in your INSTALLED_APPS and then define in your settings file the STATIC_URL which will serve as the base path that'll be used by Django to find your static files in a template. It is a good practice to have a separate static folder that will contain the assets folder which -in turn- will contain your css, js, images etc sub-folders.
So I'd take the assets folder from that path and put move it in a static folder that would be in the same level as the iddigital and templates ones. In that case your STATIC_URL variable would be equal to '/static/.
Now in the teste.html template you can load your static folder by adding {% load static %} at the top of your file. Your images can now be called as simple as this: <img src="{% static "assets/images/logocartorio.png" %}" class="bd-imagelink-1 bd-own-margins bd-imagestyles"/>
More info on the above can be found at the excellent Djangodocumentation.

Related

New to Django. Tried looking at tutorials on how to load css files and not working

The website I see when I run the server has not CSS in it, but just the HTML. So far I read that you keep CSS files in a static folder under the project directory. I have an Html template that is in the templates folder and it works perfectly when I load it from the views.home . In the HTML file, I have {% load staticfiles %} at the top of the document, and yes I have checked my installed apps for 'django.contrib.staticfiles' in the settings. Also, in the HTML document, in the href attribute I've added {% static 'style/style.css' %} which is the name of the folder under the static folder.
<!DOCTYPE HTML>
{% load staticfiles %}
<html>
<head>
<title>night_sky_2</title>
<meta name="description" content="website description" />
<meta name="keywords" content="website keywords, website keywords" />
<meta http-equiv="content-type" content="text/html; charset=windows-1252"
/>
<link rel="stylesheet" type="text/css" href="{% static 'style/style.css'
%}" />
</head>
I finally found a solution. All I had to do was add this:
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
'DjangoProjects\Sample\website\static'
)
In the settings and also moved:
{% load staticfiles %}
To the very top of the HTML document, instead of under. I put it under at first because it wasn't giving a red line which to me seems like there isn't an error.
it seems that you have done right in your html template do load the static file. Have you done this configuration in your settings.py ?
STATIC_URL = '/static/'
STATIC_ROOT = 'static'
I've read in this doc that the { % loadstatic %} has been done as {% load static %} just.
See: django docs about sttic files
Its easier than you think, but almost everyone gets it wrong the first time. There was a lightning talk about it at the DjangoCon Europe a couple of days ago: https://youtu.be/eEZYDDaDeCs?t=29m50s

Adding documentation to django app - conflict with angular

I have created documentation for my Django app using apidoc library.
It creates docs using angular. App is running on Heroku.
Docs are working nicely when I open index.html file, but I cannot open them via http://localhost:5000/docs.
Firstly I got this error:
"Variables and attributes may not begin with underscores: '__' "
, which I was able to bypass by putting {% verbatim %} and {% endverbatim %} into the index.html file. (Which I'm not very happy with in the first place and would like to do it some other way).
Then the page is stuck on the loading screen, but when I open it in Chrome I have the following error:
"Uncaught SyntaxError: Unexpected token <" in polyfill.js:1 and
require.min.js:1
And also 3 warnings:
"Resource interpreted as Stylesheet but transferred with MIME type
text/html"
in vendor/bootstrap.min.cs, vendor/prettify.css and css/style.css
We are using apidocs also in other project with Node where it works perfectly, so I think it's an issue with Django. Since the documentation is generated automatically, I would prefer to introduce changes into the app, not docs.
I tried it on Chrome and Safari.
My questions
1. What can I do to make it work?
2. How can I make Django compatible with Angular without putting {%verbatim%} tags into index.html?
Here is my controller:
from django.shortcuts import render
def show_docs(request):
return render(request, 'index.html')
and url_pattern:
from django.conf.urls import include, url
from django.contrib import admin
admin.autodiscover()
import my_app.controller
from django.views.decorators.csrf import csrf_exempt
urlpatterns = [
url(r'^docs/', my_app.controller.show_docs),
]
index.html head:
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Loading...</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="vendor/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="vendor/prettify.css" rel="stylesheet" media="screen">
<link href="css/style.css" rel="stylesheet" media="screen, print">
<link href="img/favicon.ico" rel="icon" type="image/x-icon">
<link href="css/apidoccustom.css" rel="stylesheet" media="screen, print">
<script src="vendor/polyfill.js"></script>
</head>
edit:
Thanks to answer from hubert, I was able to find the source of the problem.
It turns out, that Django doesn't work that good with RequireJS, which is used by api docs.
I had to add the following changes to the generated code to make it work:
Points 1-4 are for index.html, point 5, 6 are for main.js:
Add this line above tag:
{% load static %}
Add "{% static" + " %}" tags to all tags so it looks like this:
<link href="{% static "vendor/bootstrap.min.css" %}" rel="stylesheet" media="screen">
Add the same static tags to tags with polyfill.js and require.min.js:
<script src="{% static "vendor/polyfill.js" %}"></script>
<script data-main="{% static "main.js" %}" src="{% static "vendor/require.min.js" %}"></script>
Add {% verbatim %} at the beginning of and {% endverbatim %} at the end of , BUT BEFORE with require.min.js!
In main.js add following lines to paths at the beginning of the file:
apiProject: './api_project.js',
apiData: './api_data.js',
Change lines:
'./api_project.js',
'./api_data.js',
to:
'api_project',
'api_data',
From this two errors:
"Uncaught SyntaxError: Unexpected token <" in polyfill.js:1 and require.min.js:1
"Resource interpreted as Stylesheet but transferred with MIME type text/html"
I would assume that there is something wrong with loading your static files. Probably you have 404 or 500 on them and django loads then default route.
Check if you have correct routing for static files.

Bootstrap static files not being included in Django template

I'm new to Django, and facing issues rendering bootstrap on a django page.
This is 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 -->
<title>Dropbox Web App Prototype</title>
<!-- Bootstrap -->
<link href="{% static 'bootstrap/css/bootstrap.min.css' %}" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="jumbotron">
<h1>Hello, world!</h1>
<p>This is a template showcasing the optional theme stylesheet included in Bootstrap. Use it as a starting point to create something more unique by building on or modifying it.</p>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="{% static 'bootstrap/js/bootstrap.min.js' %}"></script>
</body>
</html>
The static file is at the same level as the project directory and has the following structure,
I've also added the following line, to my settings.py file
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),)
The CSS is not rendering on the home page. Any help appreciated.
You are using an older syntax that's probably doesn't match your version of Django.
In your html file change:
{% load staticfiles %}
to
{% load static %}
Also, replace the single quote with a double quote :
"{% static 'bootstrap/css/bootstrap.min.css' %}"
to:
"{% static "bootstrap/css/bootstrap.min.css" %}"
you can see the exact syntax of dealing with static files here
BASE_DIR is defined by default to:
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
Here __file__ is actually settings.py, so BASE_DIR is on the parent directory, the one that contains manage.py.
It seems your static folder is on another level, so just move it to the same level as manage.py and it should work.
CDN:
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous">
Static
In urls for django runserver:
if settings.DEBUG:
urlpatterns += [url(r'^static/(?P<path>.*)$', views.serve),]
When running from the webserver, you need to config an alias. Nginx example:
location /static {
alias /home/username/mysite/static;}
settings.py:
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),)
In the html
replace this
<link href="{% static 'bootstrap/css/bootstrap.min.css' %}" rel="stylesheet">
with this
<link href="/static/bootstrap/css/bootstrap.min.css" rel="stylesheet">
and check this is in the settings.
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
just define additioaly static url in your settings as follow somewhere on the bottom:
STATIC_URL = '/static/'
and check again if your bootstrap is served
can you paste your BASE_DIR ? Can you set it to: BASE_DIR to BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

How to get css and django working on live server

You guys were able to help me with last issue involving Django so I thought I'd ask another that has been killing me for the past couple days!
I have a small one app project with about 6 different pages, and I can get them to show however my style.css is not "showing" on the web page, I have followed countless guides including the Django's website and I just can't seem to get this working correctly. Here are some files that I think are relevant:
public_html/mysite/nfl/templates/home.html:
{% load staticfiles %}
<!DOCTYPE HTML>
<html lang="en">
<head>
<title> Draftr Home Page </title>
<meta charset="utf-8">
<meta name = "viewport" content="width=device-width, initial-scale=1">
<!-- Using Bootstrap 3 framework with permission from getbootstrap.com -->
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<!-- Custom Style Sheet -->
<link href="{% static 'style.css' %}" rel="stylesheet" media="screen">
style.css is located here public_html/mysite/nfl/static AND /home/gobelogic/public_html/mysite/static(alongside admin/)
/home/gobelogic/public_html/mysite/mysite:
import os.path
import sys
PROJECT_ROOT = os.path.normpath(os.path.dirname(__file__))
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
INSTALLED_APPS = (
#other
'django.contrib.staticfiles',
'nfl'
)
TEMPLATE_DIRS =
"nfl/templates",
)
STATICFILES_DIRS = (
'/home/gobelogic/public_html/mysite/nfl/static',
)
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static')
Ok I'm going to try and explain how I think django handles static files, please correct me where I'm wrong:
so in settings.py django is locating all static directories in my project and placing their contents in a single directory static/ next to manange.py(which is done when I run manage.py collectstatic
in the html file I tell django to load all the static files so that i can use them at the top by using {% load staticfiles %} and then i say which one in particular by using <link href="{% static 'style.css' %}" rel="stylesheet" media="screen"> by doing this, django uses the settings.py(?) to find where I put these static files and then loads up the stylesheet that way
Again I am running this on my production server so none of this is run through django built in server, idk if that matters or not
Thanks for any help
EDIT using django 1.8
Since you are not using Django internal server (rightly so), you need to make your production web server aware of the static file location. There is an example in Django docs for Apache (https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/modwsgi/#serving-files). Even if you are not using apache, generally you need to make sure that /static/ or whatever your STATIC_URL points to is served from the place where your STATIC_ROOT points to.

Viewing a particular html + django

I am trying to learn django by reading the tutorial and Django book on the net.
I am trying to display a web page on a url.
For the same I wrote in the url pattern function the statement (r'^home/$' , home ) where I have imported the home function.
Also in the home function I wrote
def home( request ):
return render_to_response("home.html",None) // home.html is placed in the templates folder along with its .css
This must be wrong as I don't intend to pass any response ... so please tell what i should write here...
However the issue I am facing is that when I go to the url the html comes in plain without the css styling without the color etc.....
When I check my html template however that is fine ...
So what do I need to do to display the html as it is in the url ???
Thanks..
You need to put the .css in the STATIC_FILES directory (if you are using 1.3 or MEDIA_URL for 1.2)
http://docs.djangoproject.com/en/dev/howto/static-files/
Then you need to link to the css in the head of the html file with something like:
<head>
{% load static %}
<link rel="stylesheet" href="{% get_static_prefix %}html.css" />
</head>
I assume you are using the development server.
Make sure that your URLconf is correct:
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()
See: http://docs.djangoproject.com/en/dev/howto/static-files/#serving-static-files-in-development
Then your css files can be included like this:
{% load static %}
{% get_static_prefix as STATIC_PREFIX %}
<head>
<link rel="stylesheet" href="{{ STATIC_PREFIX }}/yourpath/your.css" />
</head>
Off course the css files have to be located in your static_media dir.
This means, as stated in the docs, that you should set STATIC_ROOT to the appropriate folder, for example a folder named 'static_media' in your project directory.

Categories