Django 1.11 404 Page while Debug=True - python

Without making things difficult, I just want to show a special 404 render with staticfiles.
If you set DEBUG = False you can use in urls.py
handler404 = 'app.views.handler404'
But it is without staticfiles. I don't want to install a web server for a simple app.
With DEBUG = True in urls
url(r'^404/$', views.handler400)
is not overriding the default Page not found (404) page.
What is the easy way to achieve a render e.g. when you type localhost/asdfhjfsda with staticfiles when DEBUG=True?
Thanks in advance...

Easiest way to do this post Django 1.9 is in your urls.py:
from django.views.defaults import page_not_found
url(r'^404/$', page_not_found, {'exception': Exception()})
It wants an exception, give it an exception :)

In django 1.10 docs:
Changed in Django 1.9:
The signature of page_not_found() changed. The function now accepts a second parameter, the exception that triggered the error. A useful representation of the exception is also passed in the template context.
Have a look at your 'app.views.handler404' definition, it might miss a parameter, and maybe it's that why the r'^404/$'handler doesn't provide you with the correct method invocation.

I have a complete solution
My development environment:
Windows 7, Python 3.5.2, Django 1.11, WAMP 3.0.6 (Apache 2.4.23, mod_wsgi)
Suppose you have error_404.html template with static files
Create next directory structure ("mysite" - Django project root folder)
mysite\
mysite\
settings.py
urls.py
views.py
static\
error404\
files\
style.css
image.jpg
templates\
error404\
error_404.html
mysite\mysite\settings.py
import os
DEBUG = False
TEMPLATES = [{
..
'DIRS': [os.path.join(BASE_DIR, 'templates')],
..
}]
STATIC_URL = '/static/'
STATIC_ROOT = 'FullPathToYourSite.com/mysite/static/'
mysite\mysite\urls.py
from django.conf.urls import handler404, handler500
from . import views
urlpatterns = [..]
handler404 = views.error_404
handler500 = views.error_404
mysite\mysite\views.py
from django.shortcuts import render
def error_404(request):
return render(request, 'error404/error_404.html')
Some Jinjo logic in "error_404.html" (pseudocode)
{% load staticfiles %}
...
link type="text/css" href="{% static 'error404/files/style.css' %}"
...
img src="{% static 'error404/files/image.jpg' %}"
...

Related

I get this error when I try to render some templates in my django project, what's wrong?

I get this error when I try to render or display to a localhost the templates in my django project, and below is my error:
TemplateSyntaxError at /
Could not parse the remainder: '/style_home.css' from 'css/style_home.css'
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 4.1.3
Exception Type: TemplateSyntaxError
Exception Value:
Could not parse the remainder: '/style_home.css' from 'css/style_home.css'
Exception Location: C:\Users\Admin\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\template\base.py, line 703, in __init__
Raised during: myapp.views.home
Python Executable: C:\Users\Admin\AppData\Local\Programs\Python\Python311\python.exe
Python Version: 3.11.0
Python Path:
['D:\\IT\\Proiecte Python\\Django Site\\mysite',
'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python311\\python311.zip',
'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python311\\Lib',
'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python311\\DLLs',
'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python311',
'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages',
'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages\\win32',
'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages\\win32\\lib',
'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages\\Pythonwin']
I expected to view my html files render in the localhost site, and that's what I did
Here is my code in urls file:
from django import views
from django.contrib import admin
from myapp import views
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.home, name='home'),
path('about_me/', views.about_me, name='about_me')
]
and also I have in each html document on the first paragraph this django html line graph:
{% load static %}
because I had and some static files, and I created a static folder also with css and js:
And in the settings I have also implemented this code:
'DIRS': [BASE_DIR, 'templates'], #that's in the TEMPLATES in settings
and for static folder this lines of code:
STATIC_URL = 'static/'
STATICFILES_DIRS = BASE_DIR, 'static'
I think you are trying to include a static file using an incorrect URL.
To fix this error, you should update the URL in your HTML template to include the correct prefix for your static files. Based on the settings you've shared, the correct prefix is /static/. Here's how you can update your HTML to include the correct URL:
<link rel="stylesheet" type="text/css" href="{% static 'css/style_home.css' %}">
This code will generate a URL for your static file that includes the /static/ prefix. When the template is rendered, this URL will point to the correct location for your static files and the error should be resolved.
STATIC_URL = '/static/'
Finally, make sure that your static files are located in the correct directory. Based on the settings you've shared, you should have a directory named static in the root of your project, and inside that directory you should have a directory named css with your style_home.css file.

Build HTML from Django View

I need to construct the HTML body from a Django view and I cannot find a solution to refer correctly a JPG file ( must say that the HTML is much larger then this, but with other stuff seems that is working for me
):
I've tried this:
from django.template import Template
...
html = Template('<IMG SRC="{% static "base/images/course/website-46-2.jpg" %}">')
return HttpResponse( html )
And I get this error:
Invalid block tag on line 1: 'static'. Did you forget to register or load this tag?
In Django template I resolve this by loading the static files:
{% load static %}
How can I do this in Python ( Django View ) ? Or any other suggestion is much appreciated.
I've tried different solution that I have found on this site and others but none seems to work for me.
Django Version: 2.2.1
You can create an engine with the static library as a built-in. This makes it available to the template without calling {% load static %} first.
from django.template import Template, Context, Engine
engine = Engine(builtins=['django.templatetags.static'])
template = engine.from_string('<IMG SRC="{% static "base/images/course/website-46-2.jpg" %}">')
return HttpResponse(template.render(Context()))
Have you set your STATIC_URL in settings.py? You can do this by the following:
STATIC_URL = '/static/'
Your image would then be found under 'your_app/static/base/images/course/website-46-2.jpg'.
Does the folder structure follow this convention? If not you can set the STATIC_URL to '/base/'
def startchat(request):
template=loader.get_template('app1/chatbot.html')
return HttpResponse(template.render())
This function loads the html page into Django.
Before that , we need to import the module
from django.template import loader

Django: my css static path does not exist

My link looks like this:
<link rel="stylesheet" type="text/css" href="{% static 'css/background.css' %}">
This is fine because it gets the path I want which is href="/static/css/background.css". I use {% load static}. I have django.contrib.staticfiles in my INSTALLED_APPS. This is some more relevant info on my settings.py:
STATIC_URL = '/static/'
STATICFILES_DIR = [
os.path.join(BASE_DIR, "static"),
]
But I'm pretty sure this is right too. My problem is that static/css/background.css cannot be found by my local server. I know this because http://localhost:8000/static/css/background.css gives me a 404 error. I don't know why this is the case because this is my project file path:
Project
Project
src
static
css
background.css
Have you set your url paths ? Here is a snippet from the official Django documentation.
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
I fixed my problem and I'm posting this in case anyone this can help anyone else. My problem is that I had my static folder outside my app. It turns out that my website is targeting my app and so when django was looking for the static folder it was looking for it in my app. So try putting your static files in your app and see if that helps.

Django display user uploaded content

I have yet to wrap my head around django and URLs, and my confusion is now preventing me from doing what I feel like should be a very simple task.
I have successfully implemented file upload.
In my settings.py file, I have added the specifications for where to store the uploaded files and the URL Django should use to serve them.
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL= '/media/'
I also added the necessary line to urls.py to allow Django to serve files from MEDIA_URL.
from django.conf.urls import url, include
from django.contrib import admin
from login_app import views as login_app_views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^login/', login_app_views.login_user),
# creating registered namespaces for each app
url(r'^login/', include('login_app.urls', namespace = "login_app")),
url(r'^CMIRS/', include('dashboard_app.urls', namespace = "dashboard_app")),
url(r'^CMIRS/', include('submit_app.urls', namespace = "submit_app")),
url(r'^CMIRS/', include('filter_app.urls', namespace = "filter_app")),
url(r'^CMIRS/case/',include('report_app.urls', namespace = "report_app")),
url(r'^CMIRS/', include('search_app.urls', namespace = "search_app")),
url(r'^search/', include('haystack.urls')), ##used in navbar-search
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
In an app report_app, I want the webpage to display a hyperlink that can be used to view an uploaded file. When I click on the hyperlink, I want it to request the URL to the uploaded file.
The upload looks like such in my models:
upload1 = models.FileField(upload_to = 'documents/%Y/%m/%d/')
I am having trouble figuring out what to use in the render(request) in my view and how to correctly code this in HTML. When I attempt to use "media", I get an error saying it cannot be matched.
Here is a snippet of the HTML I am trying:
<dt>Upload</dt><dd><tr><td>{{ case.upload1 }}</td></tr></dd>
I am also confused as how to set up my render(request) so that it knows to access media/, and then go to the correct documents/Y/M/D depending on the primary key.
You don't want to use the url tag here at all. Your media's URL is stored in your model, and has nothing to do with Django's path resolution logic. Just reference the url method of the field:
<a href="{{ case.upload1.url }}">
See the docs.
(Note also that serving files via your urls.py like this works in dev only; for prod you'll need to configure your webserver to do it.)

TemplateDoesNotExist when running django app

My django app is structured as below
home/damon/dev/me/myproject/
manage.py
/mytracker/
__init__.py
settings.py
urls.py
/monitor/
/media/
/mymonitor/
__init__.py
models.py
views.py
urls.py
/templates/
base.html
home.html
In .bashrc I set PYTHONPATH as /home/damon/dev/me/myproject/
and in settings.py added these values for MEDIA_ROOT and TEMPLATE_DIR
MEDIA_ROOT = 'home/damon/dev/me/myproject/mytracker/monitor/media'
MEDIA_URL = '/site_media/'
TEMPLATE_DIRS = (
'home/damon/dev/me/myproject/mymonitor/templates'
)
mytracker.urls.py has
url(r'',include('mymonitor.urls')),
url(r'^site_media/(?P<path>.*)$','django.views.static.serve',{'document_root':settings.MEDIA_ROOT}),
whereas mymonitor.urls.py has
...
url(r'^$','mymonitor.views.home',
{'template_name':'home.html',
'page_title':'Home'
},
name='home'),
..
The base.html is extended by home.html
{% extends "base.html" %}
{% block content %}
Your Home
{% endblock %}
I think the pythonpath,locations of files everything is correctly done..Still I am getting a TemplateDoesNotExist error
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 1.4
Exception Type: TemplateDoesNotExist
Exception Value:
[{'page_title': 'Home'}, {'csrf_token': <django...
The views.py has
def custom_render(request,context,template):
req = RequestContext(request,context)
return render_to_response(req)
def home(request,template_name,page_title):
context = {'page_title':page_title}
return custom_render(request,context,template_name)
I cannot figure out why this occurs.How do I diagnose this error..? Can someone please tell me?
It should be render_to_response(template) instead of render_to_response(req).
Here is a snippet from Django documentation:
return render_to_response('my_template.html',
my_data_dictionary,
context_instance=RequestContext(request))
Also you have a relative path in TEMPLATE_DIRS when it should be absolute (that is, starting from a slash, like /home/damon/...). Because of this filesystem.Loader doesn't find your template.
And here is just an advice. TemplateResponse is much more awesome and cool then old-school render_to_response.
You should not modify TEMPLATE_DIRS in this case, because app_directories.Loader (enabled by default) should do it for you, if you have your application in INSTALLED_APPS.
You probably forget '/' in the path in TEMPLATE_DIRS ('home/...' instead should be '/home/...')
Your TEMPLATE_DIRS as you have it now is just string (in parentheses where the parentheses are ignored here), it should be a tuple so you need to add comma after your path:
TEMPLATE_DIRS = (
'/home/damon/dev/me/myproject/mymonitor/templates',
)

Categories

Resources