Django & Python报错:AttributeError: module 'blog.views'无'detail'属性
Hey there! Let's walk through how to fix this frustrating error in your Django blog project. The error tells us that your blog.urls file is trying to access views.detail, but Python can't find that function in your blog.views module—even though your code shows you've defined it!
Common Causes & Fixes
Let's go through the most likely issues step by step:
Your Django server hasn't reloaded the latest views.py changes
This is the #1 culprit. Django's dev server sometimes doesn't pick up new function definitions automatically.- Fix: Stop your server (Ctrl+C in the terminal) and restart it with
python manage.py runserver.
- Fix: Stop your server (Ctrl+C in the terminal) and restart it with
Check for typos or file naming issues
- Make sure your view file is named exactly
views.py(notview.py,Views.py, or anything else) and lives in theblogapp directory. - Double-check that the
detailfunction name is spelled correctly in bothviews.pyandurls.py—no extra spaces, uppercase letters, or typos.
- Make sure your view file is named exactly
Verify the detail function is a top-level function
From your code snippet, it looks correctly indented, but sometimes accidental nesting happens. Ensure yourdetailfunction isn't inside another function or class. It should look like this:def allblogs(request): # ... your code ... def detail(request, blog_id): # ... your code ...No extra tabs or spaces before
def detail(...).Clear Python's bytecode cache
Python stores compiled versions of your files in__pycache__folders, which can sometimes cause old code to stick around.- Fix: Delete all
__pycache__folders in your project (especially the one in theblogdirectory) and restart the server.
- Fix: Delete all
Check for name collisions
Make sure there's no other variable, class, or function nameddetailin yourviews.pythat's overriding your view function. For example, avoid code like this:# Bad: this variable overrides the detail function detail = "Some text" def detail(request, blog_id): # ... your code ...
Quick Debugging Tip
If you're still stuck, add a quick debug line at the top of your blog/urls.py to confirm what's in the views module:
from django.urls import path from . import views # Add this line to see what's available in views print("Available views:", dir(views)) urlpatterns = [ path('', views.allblogs, name='allblogs'), path('<int:blog_id>/', views.detail, name='detail'), ]
Run the server, and check the terminal output. If 'detail' isn't in the list, that confirms the function isn't being loaded properly—go back through the fixes above.
内容的提问来源于stack exchange,提问作者Spyham7

