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

Django入门开发遇ImportError:无法从__main__导入views

Fixing "ImportError: cannot import name 'views' from 'main'" in Django First Project

Hey there, let's get that Django import error sorted out—this is a super common issue when you're setting up your first project, so don't worry! I'll walk you through the root causes and fixes step by step.

Why This Error Happens

Based on the code and project structure you shared, your error has two likely culprits:

  1. A critical typo in your app's URL configuration
  2. Running the wrong file directly instead of using Django's official server command

Step 1: Fix the Typo in calc/urls.py

The biggest issue here is a misspelled variable name. You wrote urlspatterns instead of urlpatterns (missing an r). Django relies on this exact variable name to detect your app's routes, so this typo is causing all sorts of confusion, including the import error.

Here's the corrected calc/urls.py code:

from django.urls import path
from . import views

# Fixed variable name: urlpatterns (not urlspatterns)
urlpatterns = [
    path('', views.home, name='home')
]

Step 2: Run Your Project the Right Way

Never run individual app files (like calc/urls.py) directly with Python. When you do this, Python treats that file as the __main__ module, which breaks Django's relative import system (that's why you're seeing the "cannot import views from main" message).

Instead, always start your server from the root directory (where manage.py is located) using this command:

python manage.py runserver

This ensures Django loads the full project context, so relative imports like from . import views work exactly as intended.

Step 3: Quick Sanity Checks

Just to make sure everything else is set up correctly:

  • Your calc/views.py code looks perfect— the home function is properly defined and returns an HttpResponse
  • Your main project rek/urls.py correctly includes your app's URLs with include('calc.urls') (great job on that!)
  • Double-check that calc is added to INSTALLED_APPS in rek/settings.py. If it's missing, add this line:
    INSTALLED_APPS = [
        # ... other existing apps
        'calc.apps.CalcConfig',
    ]
    

If You Still Have Issues

  • Delete all __pycache__ folders in your project (they can hold old, cached code)
  • Restart your server completely
  • Confirm you're using the correct Python environment where Django is installed

内容的提问来源于stack exchange,提问作者Kalyan Mohanty

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 16:17:41