Django导入错误:无法导入'patterns',URL配置问题求助
ImportError: cannot import name 'patterns' Hey there! Let's sort out this import error you're facing. The issue here is super straightforward: Django removed the patterns function starting from version 1.10—it was deprecated in 1.8 and fully removed later, so trying to import it from django.conf.urls will throw that error.
Here's how to fix your mysite/urls.py:
Remove the
patternsimport
Update your import line to get rid ofpatternsentirely. Your imports should look like this:from django.conf.urls import include, url from django.contrib import admin from django.urls import path(If you prefer using the newer syntax, you can import
re_pathinstead ofurl—they're functionally the same, withurlbeing an alias forre_path.)Rewrite the login URL entry
The oldpatterns('login.views', ...)syntax is no longer supported. Instead, follow the same pattern you're using for your other apps (like polls, user-auth) and useincludeto point to yourloginapp'surls.pyfile. If you haven't createdlogin/urls.pyyet, make that file first—this keeps your project organized.Your updated
urlpatternsshould look like this:urlpatterns = [ path('admin/', admin.site.urls), url(r'^polls/', include('polls.urls')), url(r'^user-auth/', include('user_auth.urls')), url(r'^file-upload/', include('file_uploader.urls')), url(r'^pagination/', include('pagination.urls')), # Updated login URL using include (matches your other app setup) url(r'^login/', include('login.urls')), ]If you want to point directly to a view without using
include, just import theloginviews and reference them directly:# Add this import at the top from login import views # Then in urlpatterns: url(r'^login/', views.your_login_view_name),
Bonus: Using newer Django syntax (3.x+)
If you're on a newer Django version, it's recommended to use re_path for regex-based URLs (instead of url) and path for simple, non-regex paths. Your file would look like this:
from django.conf.urls import include from django.contrib import admin from django.urls import path, re_path from login import views urlpatterns = [ path('admin/', admin.site.urls), re_path(r'^polls/', include('polls.urls')), re_path(r'^user-auth/', include('user_auth.urls')), re_path(r'^file-upload/', include('file_uploader.urls')), re_path(r'^pagination/', include('pagination.urls')), re_path(r'^login/', include('login.urls')), # Or direct view reference: # re_path(r'^login/', views.your_login_view_name), ]
Just double-check your Django version with python -m django --version to make sure your syntax aligns with what your version supports.
内容的提问来源于stack exchange,提问作者hue pham

