Django 2认证模块的URL配置问题及代码求助
Let's walk through the problems in your music/urls.py and fix them one by one:
1. Resolve HTML Entity Escaping in Path Parameters
The most critical issue here is that you're using HTML escaped characters (< and >) instead of literal angle brackets (< and >) for path converters. Django can't parse <int:pk> as a valid path parameter—this will lead to 404 errors when trying to access the detail view.
Corrected URL Patterns:
from django.urls import path, re_path from . import views app_name = 'music' urlpatterns = [ # Authentication routes path('register/', views.register, name='register'), path('login_user/', views.login_user, name='login_user'), path('logout_user/', views.logout_user, name='logout_user'), # Fixed detail view path (replaced </> with <>) path('<int:pk>/', views.DetailView.as_view(), name='detail'), ]
2. Verify Project-Level URL Inclusion
Make sure your project's root urls.py properly includes the music app's URLs with namespace support (since you set app_name = 'music'):
from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), # Include music app URLs to enable namespace-based URL reversing path('music/', include('music.urls')), ]
Without this setup, reversing URLs using the namespace (like {% url 'music:login_user' %} in templates) will throw errors.
3. Validate View Definitions
Double-check that your views.py has the corresponding views correctly implemented:
- For
register,login_user,logout_user: Ensure these function-based views handle core authentication logic (e.g.,login_usershould validate user credentials, callauth.login(), and redirect on successful login). - For
DetailView: Confirm it's a class-based view inheriting fromdjango.views.generic.DetailView, with amodelattribute set (e.g.,model = Album) so Django knows which database model to fetch using thepkparameter.
Example of a basic valid DetailView:
from django.views.generic import DetailView from .models import Album class DetailView(DetailView): model = Album template_name = 'music/detail.html'
4. Optional: Simplify with Django's Built-In Auth Views
If you don't need fully custom authentication logic, Django 2.x provides ready-to-use auth views that eliminate boilerplate code. For example:
from django.contrib.auth import views as auth_views urlpatterns = [ # Replace custom login/logout with built-in views path('login/', auth_views.LoginView.as_view(template_name='music/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='music/logout.html'), name='logout'), # ... other routes ]
Use this approach only if it aligns with your app's requirements.
内容的提问来源于stack exchange,提问作者Themine Daha

