In my django project there are some mysterious (at least for me as a beinner) outputs I don't understand while working in my development environment.
I wanted to have a base template which includes a stylesheet in a static media folder...this works so far...but just for the address http://localhost/ all the other urls have a template which inherits from the base template.
Now the stylesheet of http://localhost/ looks nice...if i go to http://localhost/hello/ the included stylesheet has a whole html DOM structure with body, doctype etc. why is that? He somehow parses a html site instead of taking the css file...
Here my code: Any ideas?
urls.py:
from django.views.static import *
from django.conf import settings
admin.autodiscover()
urlpatterns = patterns('',
('^$',home_view),
('^hello/$', hello),
(r'^admin/', include(admin.site.urls)),
('^useragent/$',ua_display_good1),
(r'^media/(?P<path>.*)$', 'django.views.static.serve',
)
views.py
from django.http import HttpResponse
from django.shortcuts import render_to_response
def hello(request):
pagetitle = "Hello World"
return render_to_response('hello.tpl', {'pagetitle': pagetitle})
def home_view(request):
pagetitle = "Something"
return render_to_response('home.tpl', {'pagetitle': pagetitle})
def ua_display_good1(request):
try:
ua = request.META['REMOTE_ADDR']
except KeyError:
ua = 'unknown'
return render_to_response('base.tpl',{'ageone': ua})
base template:
<!DOCTYPE html>
<html lang="de">
<meta name="description=" content="{{metadescription}}">
<head>
<link rel="stylesheet" type="text/css" href="media/style.css">
<title>{% block title %}{{pagetitle}}{% endblock %}</title>
</head>
<body>
<h1>{% block h1 %}{{ageone}}{% endblock %}</h1>
{% block content %}{% endblock %}
{% block footer %}{% include "footer.tpl" %}
{% endblock %}
</body>
</html>
hello template:
{% extends "base.tpl" %}
{% block h1 %}Home{% endblock %}
{% block content %}Welcome{% endblock %}
Probably because you have a relative reference to the CSS file.
Try changing:
<link rel="stylesheet" type="text/css" href="media/style.css">
to
<link rel="stylesheet" type="text/css" href="/media/style.css">
so it always look in the root for media/style.css
Now you have set the link to css as relative "media/style.css". In home it resolves to "/media/style.css" but in hello it resolves to "/hello/media/style.css" (which gives the hello page).
Just use absolute css link like this: "/media/style.css".
The proper way to include the style sheets would be
<link rel="stylesheet" type="text/css" href="{{ MEDIA_URL }}style.css">
if this still wont work ....my css file name is Stylesheet.css and i linked it as css/Stylesheet.css ..it wasnt working... then i changed it to css/Stylesheet.CSS ..and it worked
Change href="media/style.css" to href="media/style.CSS" and it will work.
Related
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.
My question is similar to Same URL in multiple views in Django, but I am not rendering templates on the basis of user_authentication, but rather on the basis of JavaScript enabled or disabled in the browser.
What I am trying to do?
I am trying to render the index.html page if JavaScript is enabled in the browser, otherwise I want to render jsDisabled.html page if it's disabled and both of the pages should be rendered on the same URL pattern, for example:
localhost:8000 should either render index.html if JavaScript is enabled in the browser or it should render jsDisabled.html page if JavaScript is disabled.
Note: I am checking if JavaScript is disabled in the browser by using the <noscript> tag which will run when JavaScript is disabled.
Here is my code so far:
base.html:
{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
</head>
<body class="noJs">
...
abc
...
<noscript>
<style type="text/css">
.noJs {
display: none;
}
</style>
<meta http-equiv="refresh" content="{% ulr 'index' 1 %}"> /* This should render jsDisabled.html page on the same URL which is 'localhost:8000' */
</noscript>
</body>
</html>
urls.py:
from django.conf.urls import include, url
from django.contrib import admin
from . import views
urlpatterns = [
...
url(r'^(?P<flag>[0-1])$', views.index, name='index'),
]
views.py:
from django.shortcuts import render
def index(request, flag):
if (flag):
return render(request, 'jsDisabled.html')
else:
return render(request, 'index.html')
Depending on your Django version you may need to specify TEMPLATE_DIR = in settings.py (in newer versions this isn't required).
Here is some helpful information on template and tag logic:
Main/templates/myapp/base.html
Main/templates/myapp/index.html
Main/templates/myapp/includes/yes_js.html
Main/templates/myapp/includes/no_js.html
base.html:
{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
{% block content %}
{% endblock %}
</body>
</html>
index.html:
{% extends 'myapp/base.html' %}
{% load staticfiles %}
{% block content %}
<noscript>
{% include 'no_js.html' %}
</noscript>
{% include 'yes_js.html' %}
{% endblock %}
After a lot of debugging I finally found the solution :) And here it is:
base.html:
{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="noJs">
...
abc
...
</div>
<noscript>
<style type="text/css">
.noJs {
display: none;
}
</style>
{% include 'includes/jsDisabled.html' %}
</noscript>
</body>
</html>
urls.py
from django.conf.urls import include, url
from django.contrib import admin
from . import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^articles/', include('articles.urls')),
url(r'^contact/', include('contact.urls')),
url(r'^temp/',views.temp, name="temp"),
url(r'^$', views.index, name='index'),
]
views.py:
from django.shortcuts import render
def index(request):
return render(request,'index.html')
def temp(request):
return render(request,'temp.html')
I included the include built-in template tag as {% include 'includes/jsDisabled.html' %} suggested by #noes1s by creating a folder named includes inside the templates folder and placing jsDisabled.html inside of it.
I tried to link an anchor to another page in Django. But I get the error " Reverse for 'animals.all_animals' not found. 'animals.all_animals' is not a valid view function or pattern name."
I tried several ways to do it.. no success. I have one app called animals and Im tyring to display the list of animals in the by clicking an anchor on the homepage. I attached here my Django files.
from django.shortcuts import render, get_object_or_404
from .models import Animal
def animal_list(request):
animals = Animal.objects.all()
return render(request, 'animals/animal_list.html', {'animals': animals})
// and here is the html
{% for animal in animals %}
<h1>{{animal.species}}</h1>
<p>{{animal.description}}</p>
{% endfor %}
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.animal_list, name='all_animals'),
url(r'^(?P<pk>\d+)/$', views.animal_detail, name='all_details'),
]
{% load static from staticfiles %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Animals Site</title>
<link href="{% static 'css/base.css'%}" rel="stylesheet">
</head>
<body>
{% block content %}
<nav>
Animal List
</nav>
<a></a><h2>I love cats!</h2>
{% endblock content %}
{% block listbar %}
<ul>
<li>Sphynx</li>
<li>Catto</li>
<li>Bengal</li>
</ul>
{% endblock listbar %}
</body>
</html>
{% block listcolor%}
<style>
h2{
font-family: 'Calibri';
color: blue;
}
</style>
{% endblock listcolor%
You need a colon not a dot in the notation:
Animal List
Or in case the included urls from your app are not namespaced:
Animal List
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)
In my django app ,I have put these settings
settings.py
------------
MEDIA_ROOT = '/home/me/dev/python/django/myproject/myapp/media/'
MEDIA_URL = '/site_media/'
urls.py
--------
...
url(r'^myapp/', include('myapp.urls')),
url(r'^site_media/(?P<path>.*)$','django.views.static.serve',{'document_root':settings.MEDIA_ROOT}),
I created a css file in '/home/me/dev/python/django/myproject/myapp/media/css' folder and included this in template as below
base.html
--------
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>my app</title>
<LINK REL=StyleSheet HREF="{{MEDIA_URL}}css/myappstyle.css" TYPE="text/css" MEDIA="screen, print"/>
home.html
---------
{% extends "mywebapp/base.html" %}>
{% block title %}{{block.super}}| Home {% endblock %}
{% block content %}
{{block.super}}
hi
{% endblock %}
Then I created a view as below
def custom_render(request,context,template):
req_context=RequestContext(request,context)
return render_to_response(template,req_context)
def home(request,template_name,page_title):
print 'home'
return render_to_response(template_name,{'me':'myname'})
and set its url conf
myapp.urls
--------
urlpatterns=patterns('',
url(r'^$','myapp.views.home',
{
'template_name':'mywebapp/home.html',
'page_title':'Home'
},
name='home'),
when I give the url
http://127.0.0.1:8000/myapp/
The web page gets rendered ,but css is not.The console output shows a 404 error
[14/Sep/2012 10:02:50] "GET /myapp/ HTTP/1.1" 200 547
[14/Sep/2012 10:02:50] "GET /myapp/css/myappstyle.css HTTP/1.1" 404 2514
But,when I give the url,
http://127.0.0.1:8000/site_media/css/myappstyle.css
I can see the contents of the css file without any problems.
Why does this happen? can someone help me figure this out?
You need to use RequestContext() while rendering response for home view also (as you have done for custom_render view).
Otherwise {{MEDIA_URL}} will be empty which will result in 404 error.
Also you can use direct_to_template instead of render_to_response. Using it, you are not have to use RequestContext():
from django.views.generic.simple import direct_to_template
def some_view(request):
# ...
return direct_to_template(request, template_name, params_dict)
This is the static files, you need use
<LINK REL=StyleSheet HREF="{{ STATIC_URL }}css/myappstyle.css" TYPE="text/css" MEDIA="screen, print"/>
and check then DEBUG = True