You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django 2.x中urls.py导入views报错:ImportError: cannot import name 'views'

Fixing "ImportError: cannot import name 'views'" in Django 2.x

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.py file in your scheduler app directory (no typos like view.py).
  • Open views.py and confirm there are no syntax errors (missing colons, indentation issues, etc.)—a broken views.py will fail to import entirely.
  • Ensure the SchedulerView class is correctly defined in views.py, inheriting from TemplateView:
    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 between urls.py and views.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:19:09