问题
I tried this,
url ('', views.notfound, name='notfound')
But seems it doesn't work properly, for example, I have another url pattern define,
url(r'^login/$', views.login, name='login'),
So, if I go for http://example.com/login/
, this works, but if i go for http://example.com/login/?help=1
, then it falls into notfound category. How can I handle that?
回答1:
If you just want to create a page that is displayed when a URL is not found (i.e. a Http404 exception is thrown) you can create a template with the name 404.html
, and that template will be displayed any time a URL is not found.
Or if you want to define a custom 404 handler view you can define handler404 = views.notfound
in your urls.py
file. Then just create your notfound
view, and that view will be used whenever a 404 error is thrown (and DEBUG = False
)
This is a better way to catch any urls that are not recognized and display a friendly 404 page.
回答2:
You can try with regex like this:
url(r'^.*', views.notfound, name='notfound'),
Make sure put it at the end of the urls.py
I think you may need to do something when url is not found, if you just need the 404 page, then the single 404.html in your templates works. And remember ti set DEBUG = False
in your settings.py
to see the 404 page in development environment.
回答3:
Don't know what your use case is.Both above comments were equally right enough if u want to display a custom 404 page .Had u need something else to know. Check this out->
pip install django-extensions
then read this
then use the show-urls command to enlist all possible urls.
Do some manipulation or write testcases with assert to check not found urls.
Hope this is ok for your requirements or kindly comment with your suggestions cheers :-)
来源:https://stackoverflow.com/questions/27265195/how-to-write-pattern-for-all-other-urls-that-basically-goes-for-not-found-in-dja