I have the following URLConf setup:
urlpatterns = patterns('myapp.views',
url(r'^$', 'index', name="home"),
url(r'^login$', 'login'),
)
So far in my views, I have this:
def index(request):
"""Displays paginated message views"""
return HttpResponseRedirect(reverse("myapp.views.login"))
def login(request):
"""Displays login screen"""
return render_to_response('myapp/login.html', {
"title": "Login"
})
The problem arises when I try to go to the login page. Django seems to be unable to find my URL.
Going to the url http://localhost:8000/login, I receive the following error:
Page not found (404)
Request Method: GET Request
URL: http://localhost:8000/login
'login' could not be found
You're seeing this error because you have DEBUG = True in your Django
settings file. Change that to False, and Django will display a
standard 404 page.
It seems that even though I am using the reverse function to find Django's own recommended URL based on my URLConf, it is still unable to find its own URL!
Any ideas?
EDIT:
I need to clarify somethings: The problem is not that Django is unable to figure out the correct URL, it is that once that URL is loaded, Django is unable to find the view associated with that.
can you please put name attribute to your url like this
url(r'^$', 'index', name="home"),
then call reverse with this name
examples
urlpatterns = patterns('',
url(r'^archive/(\d{4})/$', archive, name="full-archive"),
url(r'^archive-summary/(\d{4})/$', archive, {'summary': True}, "arch-summary"),
)
from django.core.urlresolvers import reverse
def myview(request):
return HttpResponseRedirect(reverse('arch-summary', args=[1945]))
It turns out the error was caused by me changing the STATIC_URL variable in my settings.py file. Changing that back to "/static/" made everything work.
Related
I have two apps:
backend
shop
I my urls in main app dir:
path('backend/', include('backend.urls')),
path('', include('shop.urls')),
the problem is if I write in my url: localhost:8000/backend/abc which not exist Django jumps over to shop.urls and the app is crashing because it can not find the slug and the query goes in fail.
How can I prevent if I go to the url /backend/somethingwhichnotexist is returning an 404 and not search in other app urls for this folder? I have thought that this is one of the main reason for split the urls in app folders.
Here are some urls from backend/urls.py:
from django.urls import path, re_path
from . import views as backend_views
from django.contrib.auth import views as auth_views
from froala_editor import views
from django.conf.urls import include
urlpatterns = [
path('stamdata/', backend_views.edit_masterdata),
path('praefikser/', backend_views.edit_prefixes),
path('leverandorer/', backend_views.suppliers_view),
path('leverandorer/add', backend_views.add_supplier),
]
handler404 = 'backend.views.page_not_found_view'
shop/urls.py
here the url stops:
path('<slug:category_slug>/<slug:slug_subcategory>/', butik_views.cat_or_article),
normally I don't want that a backend urls switches to frontend view
regards
Christopher.
You you said Django run through all of the URL patterns and stops till it finds its matching URL. SO, what has happen here is that when you type a URL with localhost:8000/backend/abc/ it runs through all the URLS before returning 404 to the client. So, it stops at the URL that support any string with 2 parameters in your case below URL.
path('<slug:category_slug>/<slug:slug_subcategory>/', butik_views.cat_or_article),
To get a 404 by adding a static word in you URL.
path('shop/<slug:category_slug>/<slug:slug_subcategory>/', butik_views.cat_or_article),
or
path('backend/', include('backend.urls')),
path('shop/', include('shop.urls')),
For now I fixed it with
shop/views.py
if category_slug == 'backend':
response = render(
request,
'backend/404.html',
)
response.status_code = 404
return response
else:
until I found another solution. It looks like that the URL dispatcher is working like this:
Django runs through each URL pattern, in order, and stops at the first
one that matches the requested URL, matching against path_info.
So for now I did not found another way.
Edit:
I added this in the end of backend/urls.py:
re_path(r'^.*/$', backend_views.page_not_found_view)
so after all working urls it goes to all other to the 404 view.
Very basic question and I was surprised I wasn't able to find an answer. I'm just starting looking at django and did an out-of-box intallation. Created a project and created an app.
The default content of urls.py is very simple:
urlpatterns = [
path('admin/', admin.site.urls),
]
And if I open the django site home page, I get the content with a rocket picture. However, like I said, I have created another app in the project, let's say called 'bboard'. And I have created a simple 'hello world' function in bboard/views.py
def index(request):
return HttpResponse('Hello world')
to enable it for access through browser, I have modified the original urls.py file in the following way:
from bboard.views import index
urlpatterns = [
path('admin/', admin.site.urls),
path('bboard/', index),
]
This way I can access localhost:port/admin and localhost:port/bboard URLs, but if I try to open the home page with localhost:port now, I get Page not found error.
Using the URLconf defined in samplesite.urls, Django tried these URL patterns, in this order:
admin/
bboard/
The empty path didn't match any of these.
if I comment out the second item in urlpatterns list, everything works. So why does the additional pattern impact this and what needs to be done to fix it?
You need to add an empty url in root urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('bboard.urls'))
]
Before you add your own routes Django will serve the default home page at the '/' url. After you add your own route config, django no longer serves up its default sample home page.
From the django's django/views/debug.py:
def technical_404_response(request, exception):
"""Create a technical 404 error response. `exception` is the Http404."""
try:
error_url = exception.args[0]['path']
except (IndexError, TypeError, KeyError):
error_url = request.path_info[1:] # Trim leading slash
try:
tried = exception.args[0]['tried']
except (IndexError, TypeError, KeyError):
tried = []
else:
if (not tried or ( # empty URLconf
request.path == '/' and
len(tried) == 1 and # default URLconf
len(tried[0]) == 1 and
getattr(tried[0][0], 'app_name', '') == getattr(tried[0][0], 'namespace', '') == 'admin'
)):
return default_urlconf(request)
Note the final else block that returns a default_urlconf if the only url path included is the admin path and the requested url is /. This default_urlconf is the sample Rocket page you mentioned. As soon as you add any of your own routes the if statement in the else block will be false so the default_urlconf is not returned and instead falls through to the normal 404 handler.
Here's the default_urlconf
def default_urlconf(request):
"""Create an empty URLconf 404 error response."""
with Path(CURRENT_DIR, 'templates', 'default_urlconf.html').open() as fh:
t = DEBUG_ENGINE.from_string(fh.read())
c = Context({
'version': get_docs_version(),
})
return HttpResponse(t.render(c), content_type='text/html')
The other reason that you might be getting this error is because
You haven't passed an empty URL inside your application URL
Kindly (this is a simple but a very crucial one) check for typos
Very basic question and I was surprised I wasn't able to find an answer. I'm just starting looking at django and did an out-of-box intallation. Created a project and created an app.
The default content of urls.py is very simple:
urlpatterns = [
path('admin/', admin.site.urls),
]
And if I open the django site home page, I get the content with a rocket picture. However, like I said, I have created another app in the project, let's say called 'bboard'. And I have created a simple 'hello world' function in bboard/views.py
def index(request):
return HttpResponse('Hello world')
to enable it for access through browser, I have modified the original urls.py file in the following way:
from bboard.views import index
urlpatterns = [
path('admin/', admin.site.urls),
path('bboard/', index),
]
This way I can access localhost:port/admin and localhost:port/bboard URLs, but if I try to open the home page with localhost:port now, I get Page not found error.
Using the URLconf defined in samplesite.urls, Django tried these URL patterns, in this order:
admin/
bboard/
The empty path didn't match any of these.
if I comment out the second item in urlpatterns list, everything works. So why does the additional pattern impact this and what needs to be done to fix it?
You need to add an empty url in root urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('bboard.urls'))
]
Before you add your own routes Django will serve the default home page at the '/' url. After you add your own route config, django no longer serves up its default sample home page.
From the django's django/views/debug.py:
def technical_404_response(request, exception):
"""Create a technical 404 error response. `exception` is the Http404."""
try:
error_url = exception.args[0]['path']
except (IndexError, TypeError, KeyError):
error_url = request.path_info[1:] # Trim leading slash
try:
tried = exception.args[0]['tried']
except (IndexError, TypeError, KeyError):
tried = []
else:
if (not tried or ( # empty URLconf
request.path == '/' and
len(tried) == 1 and # default URLconf
len(tried[0]) == 1 and
getattr(tried[0][0], 'app_name', '') == getattr(tried[0][0], 'namespace', '') == 'admin'
)):
return default_urlconf(request)
Note the final else block that returns a default_urlconf if the only url path included is the admin path and the requested url is /. This default_urlconf is the sample Rocket page you mentioned. As soon as you add any of your own routes the if statement in the else block will be false so the default_urlconf is not returned and instead falls through to the normal 404 handler.
Here's the default_urlconf
def default_urlconf(request):
"""Create an empty URLconf 404 error response."""
with Path(CURRENT_DIR, 'templates', 'default_urlconf.html').open() as fh:
t = DEBUG_ENGINE.from_string(fh.read())
c = Context({
'version': get_docs_version(),
})
return HttpResponse(t.render(c), content_type='text/html')
The other reason that you might be getting this error is because
You haven't passed an empty URL inside your application URL
Kindly (this is a simple but a very crucial one) check for typos
I have a model, Position, which I have created a detail view to view each individual position.
views.py
def position_detail_view(request, id=None):
position = get_object_or_404(Position, id=id)
context= {
'object': position,
}
return render(request, 'positions/position_detail.html', context)
positions/urls.py
from django.urls import path, include
from .views import position_list_view, position_detail_view
urlpatterns = [
path('', position_list_view),
path('<int:id>', position_detail_view, name='detail')
]
When I go to http://localhost:8000/apply/1/, where the id=1, I get a Page Not Found 404 Error. However, with any other id, the page loads just fine. Any ideas on why the first id in the model gives a 404 error?
Edit 1: Traceback Error
Page not found (404) Request Method: GET Request
URL: http://localhost:8000/apply/1/ Using the URLconf defined in
bta_website.urls, Django tried these URL patterns, in this order:
admin/ [name='home'] apply/application/ apply/ apply/
[name='detail'] The current path, apply/1/, didn't match any of these.
You're seeing this error because you have DEBUG = True in your Django
settings file. Change that to False, and Django will display a
standard 404 page.
Django get_object_or_404 works like below.
get_object_or_404(klass, *args, **kwargs)
Calls get() on a given model manager, but it raises Http404 instead of the model’s DoesNotExist exception.
In your case,
your URL path is not properly configured.
Try to make changes this:
path('/<int:id>/', position_detail_view, name='detail')
Hi I have the urls like the following, here if the user hits urls which are not in my urls.py file then I need to return a 404 Error page how to do it?
urlpatterns = patterns(
'',
url(r'login$', auth.onLogin),
url(r'logout$', auth.onLogout),
......
)
Can anyone tell me how to do it?
You need just prepare 404.html template and set DEBUG=False in your settings.py
Or if you want a custom 404 page, you just need to set the 404 handler adding in your main urls.py :
handler404 = 'mysite.views.my_custom_404_view'
https://docs.djangoproject.com/en/dev/topics/http/views/#customizing-error-views
Create a 404.html file in your template folder
add this code to your view
from django.shortcuts import render
def handler404(request):
return render(request, ’404.html’)
and in urls.py
handler404 = ‘mysite.views.handler404′