Twitter bootstrap with Django 1.5 - python

I am trying to integrate Twitter bootstrap with my django application. In settings.py, I have:
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
"/path/to/my/projects/templates/static/",
)
Under the static folder, there are 3 folders namely, css, img and js and all the bootstrap files have been copied into it as is.
My template looks like so:
<html>
<head>
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'css/bootstrap-responsive.css' %}" />
<script type="text/javascript" src="{% static 'js/bootstrap.js' %}"></script>
<meta charset="utf-8">
<title>Test App</title>
</head>
<body>
<div class="navbar navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<ul class="nav">
<li class="active">
<a class="brand" href="#">TEST APP</a>
</li>
<li>About</li>
<li>Portfolio</li>
<li>Contact</li>
</ul>
</div>
</div>
</div>
How ever, when I run the development server, I get a basic html page with no change and no css applied.
What am I doing wrong here?

Assuming that your static folder is immediately underneath your Application root, this is a method that you could use to bullet-proof static file template rendering on all OSs.
import os
def replace(path):
assert isinstance(path, str)
return path.replace('\\', os.sep)
def here(*args):
return replace(os.path.abspath(os.path.join(os.path.dirname(__file__), *args)))
BASE_DIR = here('..')
def root(*args):
return replace(os.path.abspath(os.path.join(BASE_DIR, *args)))
STATICFILES_DIRS = (root('static'),)

Related

Images not appearing in Django template For Loop

See Problem Here
I want to loop over a directory of static images in Django. The images are being looped over correctly, but something is wrong with my <img src /> syntax. I've tried many variations on {{ flag }} but can't get anything to work. Can anybody advise?
In settings.py I created the following STATIC_ROOT object:
STATIC_ROOT = '/Users/TheUnforecastedStorm/Desktop/Code_projects/Portfolio_Site/portfolio_site/entrance/static'
In views.py I joined this file path to my image directory and placed the list of images in the context dictionary. I then included this dictionary in my response:
import os
from django.conf import settings
from django.shortcuts import render
# Create your views here.
def index(request):
# Create a dictionary
context = {}
# Join images directory to index.html view
flags = os.listdir(os.path.join(settings.STATIC_ROOT, "entrance/images/"))
context['flags'] = flags
# Return response
return render(request, "entrance/index.html", context)
I then looped over these images in my template:
<!DOCTYPE html>
{% load static %}
<html>
<head>
<link rel="stylesheet" href="{% static 'entrance/entrance.css' %}">
<script src="{% static 'entrance/entrance.js' %}" type="text/javascript"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
{% for flag in flags %}
<img src="{{ flag }}" alt="problem" />
{% endfor %}
</body>
</html>
#Mark1 Working off my comments from above, I haven't been able to find anything to confirm it but it seems like the {% static %} template tag can only take one extra argument to make a path, so here is something you can try.
In your view:
def index(request):
# Create a dictionary
context = {}
# Join images directory to index.html view
flags = os.listdir(os.path.join(settings.STATIC_ROOT, "entrance/images/"))
# ADD IN THIS LINE HERE
flags = ['entrance/images/'+fl for fl in flags]
context['flags'] = flags
# Return response
return render(request, "entrance/index.html", context)
The line I added in will add "entrance/images/" to the start of all the file names in the directory you are searching.
Then in your template
{% for flag in flags %}
<img src="{% static flag %}" alt="problem" />
{% endfor %}
Let me know if this works.

Static files are not loading from Static folder

I am Building a BlogApp and I am stuck on an Problem.
The Problem
Static Files are not loading from static folder. Some files are loading but some are not loading.
What have i done ?
urls.py
I also put static url in urls.py , it also didn't work for me.
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
settings.py
os.path.join(BASE_DIR, "static", "static")
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static_cdn')
my_template.html
{% load static %}
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:400,600" />
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Next Level - Gallery</title>
<!--
Next Level CSS Template
https://templatemo.com/tm-532-next-level
-->
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:400,600" />
<script src="{% static 'comments/all.min.css' %}"></script>
<script src="{% static 'comments/bootstrap.min.css' %}"></script>
<script src="{% static 'comments/templatemo-style.css' %}"></script>
</head>
<div class="row tm-welcome-row">
<div class="col-12">
<div
class="tm-welcome-parallax tm-center-child"
data-parallax="scroll"
data-image-src="static/images/blooming-bg.jpg"
>
<div class="tm-bg-black-transparent tm-parallax-overlay">
<h2>Our Gallery</h2>
<p>this is a parallax background image</p>
</div>
</div>
</div>
</div>
<div class="tm-page-col-right">
<div class="tm-gallery" id="tmGallery">
<div class="tm-gallery-item category-1">
<figure class="effect-bubba">
<img
src="static/comments/gallery/gallery-item-01.jpg"
alt="Gallery item"
class="img-fluid"
/>
</figure>
</div>
</div>
</div>
</div>
</section>
<script src="{% static 'comments/jquery.min.js' %}"></script>
<script src="{% static 'coments/parallax.min.js' %}"></script>
<script src="{% static 'comments/imagesloaded.pkgd.min.js' %}"></script>
<script src="{% static 'comments/isotope.pkgd.min.js' %}"></script>
<script src="{% static 'comments/bootstrap.min.js' %}"></script>
<script>
$(function() {
/* Isotope Gallery */
// init isotope
var $gallery = $(".tm-gallery").isotope({
itemSelector: ".tm-gallery-item",
layoutMode: "fitRows"
});
// layout Isotope after each image loads
$gallery.imagesLoaded().progress(function() {
$gallery.isotope("layout");
});
$(".filters-button-group").on("click", "a", function() {
var filterValue = $(this).attr("data-filter");
$gallery.isotope({ filter: filterValue });
console.log("Filter value: " + filterValue);
});
/* Tabs */
$(".tabgroup > div").hide();
$(".tabgroup > div:first-of-type").show();
$(".tabs a").click(function(e) {
e.preventDefault();
var $this = $(this),
tabgroup = "#" + $this.parents(".tabs").data("tabgroup"),
others = $this
.closest("li")
.siblings()
.children("a"),
target = $this.attr("href");
others.removeClass("active");
$this.addClass("active");
// Scroll to tab content (for mobile)
if ($(window).width() < 992) {
$("html, body").animate(
{
scrollTop: $("#tmGallery").offset().top
},
200
);
}
});
});
</script>
</body>
</html>
What have i tried
I also try python manage.py collectstatic and it showed 0 static files copied to 'D:\myapp\static_cdn', 248 unmodified.
I tried many answers AND some of were saying that add static url in urls.py` BUT it didn't work.
I don't know what to do
Any help would appreciated
Thank You in Advance
make sure that your settings.py has the following
settings.py
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
TEMPLATE_DIR = os.path.join(BASE_DIR,"templates")
STATIC_DIR = os.path.join(BASE_DIR,"static")
MEDIA_DIR = os.path.join(BASE_DIR, 'media')
the below preferably at the bottom end
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
STATIC_DIR,
]
#MEDIA
MEDIA_ROOT = MEDIA_DIR
MEDIA_URL = '/media/'
LOGIN_URL = 'user_login'
now create a folder called static in the base directory( the place where you have your manage.py ) and have your static files inside
make sure to {% load static %} in your template
if nothing works try opening a new project and try the above
However static files dir is different from static files directory.Django uses 2 types of static folder . system & apps
You need to put all your static files into static files dir location then run python manage.py collectstatic . It will move all your applications static files to system static folder.
Now it will served from destination(systems static files directory) location.

Using static files in a Django template

I'm trying to get a file that's in my media directory to appear on an HTML template. I'm using the "Tango with Django" book as a tutorial.
Here is my settings.py:
MEDIA_DIR = os.path.join(BASE_DIR, 'media')
MEDIA_ROOT = MEDIA_DIR
MEDIA_URL = '/media/'
Here is views.py:
def about(request):
return render(request, 'rango/about.html', )
And my about.html template:
<!DOCTYPE html>
{%load staticfiles%}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>About</title>
</head>
<body>
<h1>This is the about page</h1>
<img src="{{MEDIA_URL}} {{cat.jpg}}"
alt="cats are funny"/>
<div>
Index
</div>
</body>
</html>
I know I must be missing something very obvious, but can't figure it out for the life of me!
The {{MEDIA_URL}} tag is deprecated. Use the {% get_media_prefix %} tag, instead.
<img src="{% get_media_prefix %}cat.jpg" alt="cats are funny"/>
From the documentation:
Similar to the get_static_prefix, get_media_prefix populates a template variable with the media prefix MEDIA_URL.
When rendered, that src attribute will be equivalent to /media/cat.jpg. You may want to consider using STATIC_ROOT in your settings.py, instead, along with the {% static %} tag:
<img src="{% static 'cat.jpg' %}" alt="cats are funny"/>
I think the problems should be errors in format.
Try the following two revisions:
1. in your render(), change "return render(request, 'rango/about.html', )" to "return render(request, 'rango/about.html') by deleting the last comma;
2. in your template file about.html, change .

Django-Compressor does nothing

I am using django-compressor to compress css files.
I did as it was explained in http://django-compressor.readthedocs.org/en/latest/quickstart/
I changed my template file as follows:
{% load staticfiles %}
{% load compress %}
<!DOCTYPE html>
<html lang="en">
<head>
{% compress css %}
<link href="{% static "crsq/css/zippednewsapp/bootstrap.readable.min.css" %}" rel="stylesheet">
<link href="{% static "crsq/css/zippednewsapp/zippednewsapp.css" %}" rel="stylesheet">
<link rel="stylesheet" href="{% static "crsq/css/zippednewsapp/typeahead.css" %}"/>
{% endcompress %}
</head>
.....
I do not see any change what so ever. No error. The files are not compressed. How do I change this?
In my settings file:
DEBUG = False
TEMPLATE_DEBUG = False
STATIC_ROOT = ''
STATIC_URL = '/static/'
STATICFILES_DIRS = (
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'compressor.finders.CompressorFinder',
)
Appreciate any help. Thanks
If html didn't change, I'd check server restart after the changes.
If not, you can increase logging level and see what does the compressor module print into the logs.
Also,the compressor should run under a user with enough privileges to create files and folders under COMPRESS_ROOT (which defaults to STATIC_ROOT)
Regards

semantic UI doesn't work in django's template file

I'm writing a django website and I want to use 'Semantic UI' for its front end. but when I add a Semantic UI Button to my first page in django, it only shows plain text!
the file tree of my project is like this :
Matab->
----Matab->
--------Templates->
--------------base.html
--------------login.html
---------settings.py
-----media->
--------css->
------------semantic.css
settigs.py :
MEDIA_ROOT = os.path.join(os.path.dirname(__file__),'../media/').replace('\\','/')
MEDIA_URL = '/media/'
base.html :
<html>
<head>
<link rel="stylesheet" href="{{ MEDIA_URL }}css/semantic.css"/>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="author" content="Navid" />
</head>
<body>
<div id="mainContent">
{% block content %}{% endblock %}
</div>
</body>
</html>
login.html:
{% extends 'base.html' %}
{% block content %}
<div class="ui button">hello</div>
{% endblock %}
Edit: Please use STATIC_ROOT and STATIC_URL instead of MEDIA_ROOT and MEDIA_URL. And follow the doc to setup the static file directories.
Your MEDIA_ROOT path is wrong. Update it to this -
MEDIA_ROOT = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'media')
Here os.path.dirname(__file__) evaluates to second Matab directory. Using os.path.dirname() again, takes it to First Matab directory. Then you just join it with media. Python automatically adds the slashes.
The problem was in urls.py, I should insert this line :
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Categories

Resources