0

so I'm new to Django and I was making a webapp, named accounts. I would like to have a path method in my urlpatterns that sends me to the login page whenever I enter a url that is not mentioned in my other path methods.(NOTE: I have used the built-in login method) How do I implement?

urls.py

from django.urls import path, url
from . import views

from django.contrib.auth.views import login, logout

urlpatterns = [

    path('display/', views.display),
    path('', views.home),
    path('login/', login, {'template_name': 'accounts/login.html'}),
    path('logout/', logout, {'template_name': 'accounts/logout.html'}),
    path('register/',views.register, name='register'),
    url('xxxx', login, {'template_name': 'accounts/login.html'}) #here, I'd like to change 'xxxx'
]
  • 2
    Possible duplicate of [Redirect any urls to 404.html if not found in urls.py in django](https://stackoverflow.com/questions/30228818/redirect-any-urls-to-404-html-if-not-found-in-urls-py-in-django) – Athena Sep 05 '18 at 17:16

1 Answers1

0

You just need to create an entry in your views.py that will handle the 404:

from django.shortcuts import render_to_response
from django.template import RequestContext


def handler404(request):
    response = render_to_response('your_login_template.html', {},
                              context_instance=RequestContext(request))
    response.status_code = 404
    return response

Then in your urls.py you can specify it:

from django.conf.urls.defaults import handler404, handler500
handler404 = 'views.handler404'

Note that this will only work if DEBUG=False in your settings.py.

Athena
  • 3,200
  • 3
  • 27
  • 35
  • 1
    okay, so how do I send the control from the urls.py to the views once it doesn't find a matching entity? – N. Vakharia Sep 05 '18 at 17:18
  • @SachinKukreja yeah, good point, you need to set DEBUG=False for this to work – Athena Sep 05 '18 at 17:23
  • umm... this doesn't seem to work. I got an ALLOWED HOSTS related error, i modified it to ALLOWED_HOSTS = ['*'] but it still shows a page not found. Do i have to import a function or something? – N. Vakharia Sep 05 '18 at 17:44
  • Try setting it to localhost (where I assume you're testing) and also make sure that it wasn't redefined as [] elsewhere What's the error exactly? – Athena Sep 05 '18 at 17:51
  • Page Not Found. But it's just as a text, not as the error handling page that we usually have – N. Vakharia Sep 05 '18 at 18:04
  • Also, I am making a game which will be played by multiple people, I hope changing it to localhost won't cause an issue – N. Vakharia Sep 05 '18 at 18:06
  • Try setting the response to 200? – Athena Sep 05 '18 at 18:16