I want to redirect all pages with 404 error to another site example.com. I tried to write something like this:
handler404 = 'index.views.custom404'
def custom404(request):
return HttpResponseRedirect(reverse('index'))
But it doesn't work.
What should I write in urls.py and views.py for this operation?
Just write the fully qualified url:
handler404 = 'index.views.custom404'
def custom404(request):
return HttpResponseRedirect('http://othersite.com/custom404.html')
Related
I am trying to redirect to root URL when an app's URL is accessed without the user being logged-in.
I've tried to do so in 2 ways:
Using a decorator
#login_required(login_url = '')
def index(request):
return render(request, 'professors/index.html')
Which returned a 404 error saying the current path is accounts/login
Passing the views of the root page to redirect
def index(request):
if request.user.is_authenticated:
return render(request, 'professors/index.html')
else:
return redirect('login.views.index')
Which returned a 404 error saying the current path is professors/login.views.index
The root URL is localhost:8000/ and I am trying to redirect to it after accessing localhost:8000/professors/ when the user is not logged-in.
This problem is similar to what I've found here: Django redirect to root from a view
However, applying the solution did not work for me. It looks like when redirecting to root from an app's view, the root it is redirecting to is the app's root, and not the website's, and this is true for any URL redirected after accessing an app's URL. E.g., if the root URL is localhost:8000 and the app's URL is localhost:8000/professors/, then trying to access any other URL from the latter, will mean that localhost:8000/professors/ is the starting point and what I write in the login_url or redirect(redirect_URL) is added to that, which means that I can no longer access localhost:8000
Final note:
When I tried return redirect ('') in else it returned
NoReverseMatch at /professors/
Reverse for '' not found. '' is not a valid view function or pattern name.
Which shows that the starting point is again from localhost:800/professors/
Set your login_url parameter in login_required decorator,
#login_required(login_url='/')
def index(request):
return render(request, 'professors/index.html')
You can also set the LOGIN_URL in settings
#settings.py
LOGIN_URL='/'
I am trying to override the default 403.html template of django rest framework, by declaring in ulrs.py handler403 = 'my_app.views.handler403'.
And in the app's views.py:
def handler403(request, exception, template_name='403.html'):
response = render_to_response('403.html', {})
response.status_code = 403
return response
The template's directory is included in TEMPLATE_DIRS in settings.py.
However, making a request to an endpoint that has IsAdminUser permission, renders the default drf template.
The same exact procedure for the 404 exception works perfectly fine.
Any answer I saw in the web did not help me resolve the issue.
It's quite simple actually:
You have to overwrite 'custom_exception_handler' of the DRF just like below:
from Django.shortcuts import render_to_response
def custom_exception_handler(...):
response = render_to_response('path/to/template/403.html', {})
response.status_code = 403
return response
It does not work because DRF returns a json response, does not render a template.
try this:
from django.shortcuts import render
def handler403(request, exception, template_name='403.html'):
return render(request, '403.html')
I am new to Python and Django. I did a experiment on enforcing request method (e.g. for certain url you can only use GET). Here is my code.
tests.py
from django.test import TestCase, Client
client = Client()
class MyTests(TestCase):
def test_request_method:
""" Sending wrong request methods should result in 405 error """
self.assertEqual(client.post('/mytest', follow = True).status_code, 405)
urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name = 'index'),
url(r'^mytest/', views.mytest, name = 'mytest'),
]
views.py
from django.http import HttpResponse
def mytest(request):
if request.method == 'GET':
return HttpResponse("Not implemented", status = 500)
else:
return HttpResponse("Only GET method allowed", status = 405)
But the test always returns status 500.
I saw here that this may be related to using follow=True in the client.post() call. However if I use follow=False I will get status 301 instead.
Any ideas? Thank you!
Does it perhaps redirect /mytest to /mytest/? The documentation suggests that by default, a trailing slash is added by doing a redirect if no URL pattern matches without the slash, and to quote:
Note that the redirect may cause any data submitted in a POST request to be lost.
A request caused by commonly used redirect status codes is always a GET request. You could either make the request to /mytest/ or remove the trailing slash from your URL pattern.
I'm in c.html (http://localhost:8000/practice/c) and I click a link that changes my url to
http://localhost:8000/practice/c/?q=1
this is urls.py
url(r'^$', prac_c),
url(r'^q=\d',fetch_c),
and this is views.py
def prac_c(request):
return render_to_response('subject/c.html', {"problem_list":problem_list})
def fetch_c(request):
qno = request.GET.get('q')
if qno:
return render_to_response('subject/que.html', {'qno':qno}, context_instance=RequestContext(request))
but I'm not getting directed to que.html. Something wrong with the urls.py?
What the URLconf searches against
The URLconf searches against the requested URL, as a normal Python string. This does not include GET or POST parameters, or the domain name.
source
I have this method in my book model:
def get_absolute_url(self):
return "/book/%s/%s/%i/%i/" % ( self.book_title, self.book_editor, self.book_pages, self.id)
So the urls of each book are like this:
example.com/book/the-bible/gesu-crist/938/12/
I want that if there is an error in the url, then I get redirected to the real url by using book.id in the end of the url.
For example if I go to:
example.com/book/A-bible/gesu-crist/938/12/
the I will get redirected to:
example.com/book/the-bible/gesu-crist/938/12/
How can I do that ?
You could create custom HTTP 404 handler.