Skip to content

Instantly share code, notes, and snippets.

@Khnaz35
Created May 20, 2024 11:41
Show Gist options
  • Save Khnaz35/cd070e0770f7f2d0dc2f4d5e1e1dc4c5 to your computer and use it in GitHub Desktop.
Save Khnaz35/cd070e0770f7f2d0dc2f4d5e1e1dc4c5 to your computer and use it in GitHub Desktop.
Failed to resolve the URL for 'dashboards:index'.
_keenthemes/urls.py
import logging
from django.urls import include, path
from django.conf import settings
from _keenthemes.views import SystemView
logger = logging.getLogger(__name__)
logger.debug("Loading main URL patterns")
urlpatterns = [
path('', include('dashboards.urls', namespace='dashboards')),
path('', include('auth.urls', namespace='auth')),
]
logger.debug("Included dashboards.urls")
logger.debug("Included auth.urls")
handler404 = SystemView.as_view(template_name='pages/' + settings.KT_THEME + '/system/not-found.html', status=404)
handler500 = SystemView.as_view(template_name='pages/' + settings.KT_THEME + '/system/error.html', status=500)
_keenthemes/urls_public.py
"""_keenthemes URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
#urls_public.py
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from _keenthemes.views import SystemView
urlpatterns = [
path('admin/clearcache/', include('clearcache.urls')),
path('admin/', admin.site.urls),
# public app urls
path('', include('public.urls', namespace='public')),
# Auth urls
path('', include('auth.urls', namespace='auth')),
]
handler404 = SystemView.as_view(template_name = 'pages/' + settings.KT_THEME + '/system/not-found.html', status=404)
handler500 = SystemView.as_view(template_name = 'pages/' + settings.KT_THEME + '/system/error.html', status=500)
dashboards/urls.py
#dashboards/urls.py
from django.urls import path
from dashboards.views import DashboardsView
app_name = 'dashboards'
urlpatterns = [
path('index', DashboardsView.as_view(template_name='pages/dashboards/index.html'), name='index'),
path('error', DashboardsView.as_view(template_name='non-exist-file.html'), name='error'),
]
auth/urls.py
#auth/urls.py
from django.urls import path
from django.conf import settings
from auth.signin.views import AuthSigninView
from auth.signup.views import AuthSignupView
from auth.reset_password.views import AuthResetPasswordView
from auth.new_password.views import AuthNewPasswordView
from auth.emails.views import AuthVerifyEmailView
app_name = 'auth'
urlpatterns = [
path('signin', AuthSigninView.as_view(template_name = 'pages/auth/signin.html'), name='signin'),
path('signup', AuthSignupView.as_view(template_name = 'pages/auth/signup.html'), name='signup'),
path('reset-password', AuthResetPasswordView.as_view(template_name = 'pages/auth/reset-password.html'), name='reset-password'),
path('new-password', AuthNewPasswordView.as_view(template_name = 'pages/auth/new-password.html'), name='new-password'),
path('verify-email', AuthVerifyEmailView.as_view(template_name = 'pages/auth/email-verified.html'), name='verify-email'),
]
dashboards/views.py
from django.views.generic import TemplateView
from django.http import HttpResponse
from django.conf import settings
from django.urls import resolve
from _keenthemes.__init__ import KTLayout
from _keenthemes.libs.theme import KTTheme
from pprint import pprint
class DashboardsView(TemplateView):
template_name = 'pages/dashboards/index.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context = KTLayout.init(context)
KTTheme.addVendors(['amcharts', 'amcharts-maps', 'amcharts-stock'])
return context
The code which is causing the issue.
auth/signin/views.py
from django.urls import reverse, get_resolver, NoReverseMatch
from django.shortcuts import redirect
from django.views.generic import TemplateView
from django.http import JsonResponse
from django.contrib.auth import authenticate
from auth.models import User
from auth.tasks import populate_session_data, generate_and_cache_refresh_token
from django.utils import timezone
from _keenthemes.__init__ import KTLayout
from _keenthemes.libs.theme import KTTheme
from _keenthemes.services.cache_manager import CacheManager
import logging
logger = logging.getLogger(__name__)
cache_manager = CacheManager()
class AuthSigninView(TemplateView):
template_name = 'pages/auth/signin.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context = KTLayout.init(context)
KTTheme.addJavascriptFile('js/custom/authentication/sign-in/general.js')
context.update({
'layout': KTTheme.setLayout('auth.html', context),
})
return context
def post(self, request, *args, **kwargs):
logger.debug(f"Registered namespaces at the start: {get_resolver(None).namespace_dict.keys()}")
email = request.POST.get('email', '')
password = request.POST.get('password', '')
logger.debug(f"Received email: {email}")
logger.debug(f"Received password: {'*' * len(password)}") # Mask password length for privacy
user = authenticate(email=email, password=password)
if user:
logger.debug(f"User {email} authenticated successfully.")
cached_token = cache_manager.get_cached_refresh_token(user.id)
logger.debug(f"Cached token for user {user.id}: {cached_token}")
if not cached_token or timezone.now() >= cached_token['expires_at'] - timezone.timedelta(days=5):
logger.debug("Cached token is either missing or about to expire, generating a new token.")
result = generate_and_cache_refresh_token.delay(user.id, user.tenant.id)
try:
cached_token = result.get(timeout=10)
logger.debug(f"Generated new refresh token for user {user.id}: {cached_token}")
except Exception as e:
logger.error(f"Error generating refresh token for user {user.id}: {e}")
return JsonResponse({'status': 'error', 'message': 'Failed to generate refresh token.'}, status=500)
else:
logger.debug("Using existing cached token.")
if cached_token:
session_id = populate_session_data(user.id, user.tenant.id, cached_token['token'])
logger.debug(f"Session data populated for user {user.id}, session ID: {session_id}")
response = JsonResponse({'status': 'success'})
response.set_cookie('sessionid', session_id, httponly=True, secure=True, samesite='Strict')
logger.debug(f"Set session cookie for session ID: {session_id}")
tenant_id = user.tenant.id
if tenant_id:
request.tenant_id = tenant_id
logger.debug(f"Tenant ID set in request: {tenant_id}")
else:
logger.error("Tenant ID attribute not found in the request.")
return JsonResponse({'error': 'Tenant ID attribute missing in request.'}, status=500)
try:
redirect_url = reverse('dashboards:index')
logger.debug(f"Reverse URL for dashboards:index: {redirect_url}")
except NoReverseMatch as e:
logger.error(f"Failed to resolve the URL for 'dashboards:index'. Error: {e}")
return JsonResponse({'error': 'Dashboard URL resolution error.'}, status=400)
logger.debug(f"Redirecting to: {redirect_url}")
response = redirect(redirect_url)
response.set_cookie('sessionid', session_id, httponly=True, secure=True, samesite='Strict')
logger.debug(f"Redirected to: {redirect_url}")
return response
else:
logger.error(f"Failed to generate or retrieve refresh token for user {user.id}.")
return JsonResponse({'status': 'error', 'message': 'Failed to generate refresh token.'}, status=500)
else:
logger.error(f"Authentication failed for email: {email}.")
return JsonResponse({'status': 'error', 'message': 'Authentication failed'}, status=401)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment