Django入门开发遇ImportError:无法从__main__导入views
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:
- A critical typo in your app's URL configuration
- 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.pycode looks perfect— thehomefunction is properly defined and returns anHttpResponse - Your main project
rek/urls.pycorrectly includes your app's URLs withinclude('calc.urls')(great job on that!) - Double-check that
calcis added toINSTALLED_APPSinrek/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

