Django 404.html for mobile site - django

My django site is having web & mobile versions. I have enabled debug setting false which returns templates 404.html whenever the requested page is not found. I would like to modify the view function to return 2 different 404 html pages like 404.html/404mobile.html based on platform.
Detecting user browser through JavaScript in 404.html page did not help as my 404.html page has header and footer extends from base html file.
Modifying views will solve this? If so where is the debug setting class file residing in Django package?

Here is the function using user_agent ..
from user_agents import parse
def idfy(request):
user_agent = parse(ua_string)
if user_agent.is_mobile:
return HttpResponse('I m n mobile')
else:
return HttpResponse('I m n pc')

from django.conf.urls import patterns, include, url
from django.views.static import *
from django.conf import settings
from django.conf.urls.defaults import handler404
from app.views import error
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'app.views.home', name='home'),
)
handler404 = error.error_handler
overriding handler404 method resolves this issue

Related

Python - Django add multiple urlpatterns for multiple views of template

I'm very very new to Python 3 and Django and I get to the following problem: I use a standard Template and now how to set it up when there is 1 view. But I don't get the code right for multiple views. I currently run the page locally
At the moment I have tried to change different orders within urlpatterns, and they do work when only 1 url in in there, but I can't get the second one in
views.py
from django.shortcuts import render, render_to_response
# Create your views here.
def index(request):
return render_to_response('index.html')
def store(request):
return render_to_response('store.html')
urls.py
from django.conf.urls import include, url
from django.contrib import admin
from myapp import views as views
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^store/$', views.store, name='store'),
url(r'^admin/', admin.site.urls)
]
urlpatterns += staticfiles_urlpatterns()
I would like the url pattern that lets me go to the index view and the store view
EDIT:
Full code is shared via: https://github.com/lotwij/DjangoTemplate
The error in the comments shows you are going to http:/127.0.0.1:8000/store.html, but your URL pattern url(r'^store/$', ...) does not include the .html, so you should go to http:/127.0.0.1:8000/store/.
The Django URL system uncouples the URL from the name of the template (sometimes the view doesn't even render a template!). You could change the regex to r'^store.html$ if you really want .html in the URL, but I find the URL without the extension is cleaner.

django 'admin' is not a registered namespace in pybbm-forum app on subdomain

I have django 1.10.7, python2.7, installed django-hosts, pybbm app.
Pybbm forum on subdomain forum.example.com.
When i'l trying open topic on url forum.example.com/topic/1/, that already have created, i get error.
NoReverseMatch at /topic/1/
u'admin' is not a registered namespace
my hosts.py
# -*- coding: utf-8 -*-
from django_hosts import patterns, host
from django.conf import settings
host_patterns = patterns('',
host(r'example.com', settings.ROOT_URLCONF, name='www'),
host(r'forum', 'forums.urls', name='forum'),
)
my forums/urls.py, where i included pybb urls
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
url(r'^', include('pybb.urls', namespace='pybb')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Can you help how to better configure pybbm forum app with my django project on subdomain?
Looks like you have no admin url in your 'forums/urls.py' and the template that renders '/topic/1/' has some django url link pointing to admin routes (e.g. Foo) that doesn't even exist. Can you show the template code?

Django 1.9 broken redirect after custom 404 page

On Django 1.9 multilingual site domain.com/ used to redirect to domain.com/en/ automatically.
Now, when I put a custom 404.html in top level templates dir, Django no longer redirects to the language:
domain.com/ throws server error 500 instead of redirecting to domain.com/en/
How keep custom 404 error page and get no server error 500?
Code:
urls:
from django.conf.urls import url, include
from django.contrib import admin
from django.http import HttpResponse
from django.conf.urls.i18n import i18n_patterns
urlpatterns = [
url(r'^robots\.txt$', lambda r: HttpResponse(" ", content_type="text/plain"))
]
urlpatterns += i18n_patterns(
url(r'^admin/', admin.site.urls),
url(r'^rosetta/', include('rosetta.urls')),
url(r'^', include('mp.urls', namespace='mp', app_name='mp')),
)
Dirs:
- project_folder
- app
-- templates
--- app_name
---- all templates
--- 404.html (had to put higher than app subdir, for Django to see it)
- project
-- settings, etc
view:
class Main(View):
def get(self, request):
c = get_seo_stuff("home")
t = "app/home.html"
return render(request, t, c)
def post(self, request):
pass
Code is pretty simple and it used to work just before the 404.html commit.
Figured it out. It was a multisite Django installation, and when I added a custom 404.html in one app, Django tried showing it on other apps as well.
The 404.html contained urls and stuff, not resolvable from the other tenant apps, resulting in Server Error 500.
Solution: add custom 404 handlers or use neutral 404.html page.

django urls: "Django tried these URL patterns"

I am trying a tutorial on Django called blog. I have the following structure:
FirstBlog|FirstBlog
settings
urls
__init__
etc
blog
templates | index.html
migrations
views.py
manage.py
The view.py has
from django.shortcuts import render
from django.shortcuts import render_to_response
from blog.models import posts
def home(request):
return render('index.html')
The urls.py has
from django.conf.urls import url
from django.conf.urls import include
from django.contrib import admin
urlpatterns = [
url(r'^blog', 'FirstBlog.blog.views.home',name='home'),
]
and I get this error:
Using the URLconf defined in FirstBlog.urls, Django tried these URL patterns, in this order: ^blog [name='home']
The current URL, , didn't match any of these.
I can't seem to get it right..
Any help would be appreciated.
Thank you,
You are requesting for / url and you have not saved any such mapping. Current mapping is for /blog . So it will work for the same url.
i.e goto the browser and request /blog
If you need it to work for / then change the urls appropriately.
within your blog app, create a urls.py file and add the following code which calls the home view.
blog/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
#url(r'^',views.home, name='home'),
]
then in your root urls file which can be found at FirstBlog/urls.py
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^blog/',include('blog.urls')), #when you visit this url, it will go into the blog application and visit the internal urls in the app
]
PS:
your templates should be in blog/templates/blog/index.html
Read this docs on templates to understand how django locates templates.
This one is to understand how urls work Urls dispatcher
You are doing this in the wrong way! Try doing that using TemplateView from class-based views, which are the current standard from django views.
Check the django documentation: https://docs.djangoproject.com/en/1.9/topics/class-based-views/
Use this at the urls.py:
from django.conf.urls import url
from django.views.generic import TemplateView
urlpatterns = [
url(r'^blog/', TemplateView.as_view(template_name="index.html")),
]
And then, create a folder called templates in the project root ( like this: https://docs.djangoproject.com/en/1.9/intro/tutorial03/#write-views-that-actually-do-something ) named index.html
Simply go to file then select Save all your project instead of save. Or use shortcut Ctrl +k s on windows. Project should be able to sync and display the code on Django interface

Custom Django 404 error

I have a 404.html page, but in some cases I want to be able to send a json error message (for 404 and 500, etc.). I read the following page:
https://docs.djangoproject.com/en/dev/topics/http/views/#the-404-page-not-found-view
Is there any sort of example that shows the implementation? I have it in my urls.py but it's not being picked up in the event of an error.
This worked for me:
from django.conf.urls import patterns, include, url
from django.views.static import *
from django.conf import settings
from django.conf.urls.defaults import handler404, handler500
from app.views import error
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'app.views.home', name='home'),
)
handler404 = error.error_handler
handler500 = error.error_handler
You can make it do anything as you wish when going to that controller.
In addition to the previous answer, it is important to say that the views.py should return a HttpResponse with a 404 status in the http header. It is important to inform the search engines that the current page is a 404. Spammers sometimes creates lots of urls that could seem that would lead you to some place, but then serves you another content. They frequently make lots of different addresses serve you almost the exact same content. And because it is not user friendly, most SEO guide lines penalize that. So if you have lots of addresses showing the same pseudo-404 content, it could not look good to the crawling systems from the search websites. Because of that you want to make sure that the page you are serving as a custom 404 has a 404 status. So here it is a good way to go:
Into your application's urls.py add:
# Imports
from django.conf.urls.static import static
from django.conf.urls import handler404
from django.conf.urls import patterns, include, url
from yourapplication import views
##
# Handles the URLS calls
urlpatterns = patterns('',
# url(r'^$', include('app.homepage.urls')),
)
handler404 = views.error404
Into your application's views.py add:
# Imports
from django.shortcuts import render
from django.http import HttpResponse
from django.template import Context, loader
##
# Handle 404 Errors
# #param request WSGIRequest list with all HTTP Request
def error404(request):
# 1. Load models for this view
#from idgsupply.models import My404Method
# 2. Generate Content for this view
template = loader.get_template('404.htm')
context = Context({
'message': 'All: %s' % request,
})
# 3. Return Template for this view + Data
return HttpResponse(content=template.render(context), content_type='text/html; charset=utf-8', status=404)
The secret is in the last line: status=404
Hope it helped!
I look forward to see the community inputs to this approach. =)
Basics:
To define custom view for handling 404 errors, define in the URL config, a view for handler404, like handler404 = 'views.error404'
Apart from the basics, some things to note about (custom 404 views):
It will be enabled only in Debug=False mode.
And more ignored one, across most answers (and this this stuck my brains out).
The 404 view defaults to
django.views.defaults.page_not_found(request, exception, template_name='404.html')
Notice the parameter exception
This was causing a 404 to 500 redirect from within def get_exception_response(self, request, resolver, status_code, exception) function defined in core.handlers.base since it could not find the parameter exception