I have imported a front-end project including completed .css, .js, .html files into Django templates. They can work when run .html directly. But if run them in Django server, all links with relative path should be modified as Django style such as
<link rel="stylesheet" type="text/css" href="{% static 'style.css' %}" />
instead of
<link rel="stylesheet" type="text/css" href="css/style.css" />.
Is there any method to keep the orginal relative path in .html file and also can run in Django?
===========================================================================
I've solve my problem, the solutions are add their path into urls.py under primary program.
if settings.DEBUG:
urlpatterns += [
url(r'^(?P<path>css.*)$', views.serve),
url(r'^(?P<path>images.*)$', views.serve),
url(r'^(?P<path>js.*)$', views.serve)]
Related
Been through every question asked here on same topic, but couldn't get my issue resolved. I have a project (modified version of this) directory setted up this way;
I have two links to go to from home page
Admin Dashboard
Dashboard
The admin dashboard page is prefixed by /admin/dashboard whereas the other is /dashboard. I am creating home blueprint (inside home.init.py) by providing the relative path of root static directory;
home = Blueprint('home', __name__, static_url_path='/app/static', static_folder="static")
both the home page and the dashboard page can find the static directory (and load properly), but the admin/dashboard CANNOT fetch static/ resources from admin/static/: GET http://127.0.0.1:5000/admin/static/vendors/bootstrap/dist/js/bootstrap.min.js. the strange thing is, I later added the entire static folder inside admin directory but still it cannot find the above bootstrap.min.js link. Here is my app/init.py file where I am registering the blueprints with app
from .admin import admin as admin_blueprint
app.register_blueprint(admin_blueprint, url_prefix='/admin')
from .home import home as home_blueprint
app.register_blueprint(home_blueprint)
and home/views.py
#home.route('/dashboard')
#login_required
def dashboard():
"""
Render the dashboard template on the /dashboard route
"""
return render_template('home/dashboard.html', title="Dashboard")
#home.route('/admin/dashboard')
#login_required
def admin_dashboard():
prevent non-admins from accessing the page
if not current_user.is_admin:
abort(403)
return render_template('home/admin_dashboard.html', title="Admin Dashboard")
the base.html is listed with some static resources to load.
<link href="{{ url_for('static', filename='vendors/bootstrap/dist/css/bootstrap.min.css') }}" rel="stylesheet">
<link href="{{ url_for('static', filename='vendors/font-awesome/css/font-awesome.min.css') }}" rel="stylesheet">
<link href="{{ url_for('static', filename='vendors/themify-icons/css/themify-icons.css') }}" rel="stylesheet">
<link href="{{ url_for('static', filename='vendors/flag-icon-css/css/flag-icon.min.css') }}" rel="stylesheet">
<link href="{{ url_for('static', filename='vendors/selectFX/css/cs-skin-elastic.css') }}" rel="stylesheet">
<link href="{{ url_for('static', filename='vendors/jqvmap/dist/jqvmap.min.css') }}" rel="stylesheet">
According to the docs, providing the static_url_path to prefixed pages should work, do anyone have a clue on what happening wrong here. Any help would be appreciated. Thanks
I'm experimenting with django-distill (https://github.com/mgrp/django-distill) to generate a static site from a django project. i'm using django 1.10.8 . My main template contains:
<!-- Bootstrap Core CSS -->
{% load staticfiles %}
<link href="{% static "css/bootstrap.min.css" %}" rel="stylesheet" />
<!-- Custom CSS -->
<link href="{% static "css/landing-page.css" %}" rel="stylesheet" />
<link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/jquery.slick/1.5.0/slick.css"/>
The paths to the css and js files are correct when I run the project locally on my windows system. However when I look at the source html I see:
on my windows system this works with a running sever, i.e.
http://127.0.0.1:8000/static/css/bootstrap.min.css
but it breaks with static files and I have to change these to
<link href="./static/css/bootstrap.min.css" rel="stylesheet" />
Is there any way to set % static to render to
./static/ instead of /static/
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.
I have the following structure in my Django project. As you can see, there is one app called "blog" as well as the main app that is eponymous with the project itself.
The problem I am having has to do with serving static files from the static directory of the main project. The blog app has its own static directory and those files are served properly (when the pertinent URL routes are traversed).
Could someone tell me what I am doing wrong? Also, what is the best practice of serving static files when dealing with multiple apps? Is it prudent to dump all styles and scripts into a common static directory in the root of the project or is it better to keep things entirely separated from app to app?
settings.py
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_ROOT = os.path.join(BASE_DIR, "..", "django_by_example_blog", "static")
STATIC_URL = '/static/'
urls.py
urlpatterns = [
url(r'^$', TemplateView.as_view(template_name="base.html")),
url(r'^admin/', include(admin.site.urls)),
url(r'^blog/', include('blog.urls', namespace='blog', app_name='blog')),
]
base.html
{% load staticfiles %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<title>Home | Triangle</title>
<link href="{% static "css/bootstrap.min.css" %}" rel="stylesheet">
<link href="{% static "css/font-awesome.min.css" %}" rel="stylesheet">
<link href="{% static "css/animate.min.css" %}" rel="stylesheet">
<link href="{% static "css/lightbox.css" %}" rel="stylesheet">
<link href="{% static "css/main.css" %}" rel="stylesheet">
<link href="{% static "css/responsive.css" %}" rel="stylesheet">
<!--[if lt IE 9]>
<script src="{% static "js/html5shiv.js" %}></script>
<script src="{% static "js/respond.min.js" %}"></script>
<![endif]-->
<link rel="shortcut icon" href="{% static "images/ico/favicon.ico" %}">
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="{% static "images/ico/apple-touch-icon-144-precomposed.png" %}">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="{% static "images/ico/apple-touch-icon-114-precomposed.png" %}">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="{% static "images/ico/apple-touch-icon-72-precomposed.png" %}">
<link rel="apple-touch-icon-precomposed" href="{% static "images/ico/apple-touch-icon-57-precomposed.png" %}">
</head><!--/head-->
<body>
STATIC_ROOT specifies the folder into which all static files will be dumped when you run the collectstatic command
python manage.py collectstatic
You seem to have specified one of your app's static folder as the static_root.
It would be preferable to give another folder for holding all your static files.
STATIC_ROOT = os.path.join(BASE_DIR, "static")
when you run the collectstatic command it would collect all your static files and place them into the STATIC_ROOT folder.
Although, while running in DEBUG=True you needn't worry about any of this.
Django will serve all the static content (including from within individual apps), but in a production environment this is not recommended and it would be the job of the web server to serve static content.
EDIT:
You also need to specify in your base urls.py
from django.conf.urls.static import static
from django.conf import settings
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
"Dumping all styles and scripts into a common static directory" is exactly what the collectstatic command does. You should run that, and configure your server to serve the files from there.
First though you should set your STATIC_ROOT setting to point to that common directory, rather than inside your app.
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.