Django 2.x中urls.py导入views报错:ImportError: cannot import name 'views'
It sounds like you're hitting an import issue that's more strictly enforced in Django 2.x compared to older versions, even though your code looks like a standard implementation. Let's break down the possible causes and fixes:
1. Verify Basic File Structure & Syntax
First, double-check the fundamentals:
- Make sure there's a
views.pyfile in yourschedulerapp directory (no typos likeview.py). - Open
views.pyand confirm there are no syntax errors (missing colons, indentation issues, etc.)—a brokenviews.pywill fail to import entirely. - Ensure the
SchedulerViewclass is correctly defined inviews.py, inheriting fromTemplateView:from django.views.generic.base import TemplateView class SchedulerView(TemplateView): template_name = "scheduler/your_template.html" # Update to your actual template path # Add your custom logic here
2. Check for Circular Imports
Django 2.x is stricter about circular dependencies than older versions. If your views.py imports anything from the urls.py of the same app (e.g., from . import urls or from scheduler import urls), this creates a circular loop that triggers the ImportError.
Fix:
- Extract shared logic into a separate module (like
utils.py) and import from there instead of directly betweenurls.pyandviews.py.
3. Adjust Your Import Statement
Instead of importing the entire views module, try importing the specific view class directly with an absolute import:
from django.urls import path, re_path from scheduler.views import SchedulerView # Absolute import of the view class app_name = 'scheduler' urlpatterns = [ re_path(r'^service/(?P<status>\w+)', SchedulerView.as_view(), name='schedule-service') ]
This avoids any ambiguity with relative imports and can bypass issues related to module-level circular dependencies.
4. Use Django 2.x's Preferred Routing Syntax
While not directly related to the import error, Django 2.x introduced path() with path converters as a cleaner alternative to re_path(). You can rewrite your route like this:
path('service/<str:status>/', SchedulerView.as_view(), name='schedule-service')
Adding the trailing / aligns with Django's URL best practices and prevents unexpected routing behavior.
内容的提问来源于stack exchange,提问作者mkjwa

