我正在学习教科书《Python 速成课程第三版》,我检查了我的代码,一切看起来都是正确的,但是当我 python manage.py runserver 时,我收到了错误。
from django.shortcuts import render, redirect
# Create your views here.
from .models import Topic
from .forms import TopicForm, EntryForm
def index(request):
"""The home page for learning Log."""
return render(request, 'learning_logs/index.html')
def topics(request):
"""Show all topics."""
topics = Topic.objects.order_by('date_added')
context = {'topics': topics}
return render(request, 'learning_logs/topics.html', context)
def topic(request, topic_id):
"""Show a single topic and all its entries."""
topic = Topic.objects.get(id=topic_id)
entries = topic.entry_set.order_by('-date_added')
context = {'topic': topic, 'entries': entries}
return render(request, 'learning_logs/topic.html', context)
def new_topic(request):
"""Add a new topic"""
if request.method != 'POST':
# No data submitted; create a blank form.
form = TopicForm()
else:
# POST data submitted; process data.
form = TopicForm(data=request.POST)
if form.is_valid():
form.save()
return redirect('learning_logs:topics')
# Display a blank or invalid form.
context = {'form: form'}
return render(request, 'learning_logs/new_topic.html', context)
def new_entry(request, topic_id):
"""Add a new entry for a particular topic."""
topic = Topic.objects.get(id=topic_id)
if request.method != 'POST':
# No data submitted; create a blank form.
form = EntryForm()
else:
# POST data submitted; process data.
form = EntryForm(data=request.POST)
if form.is_valid():
new_entry = form.save(commit=False)
new_entry.topic = topic
new_entry.save()
return redirect('learning_logs:topic', topic_id=topic_id)
# Display a blank or invalic form.
context = {'topic': topic, 'form': form}
return render(request, 'learning_logs/new_entry.html', context)type here
The learning_logs/urls
from django.urls import path
from . import views
app_name = 'learning_logs'
urlpatterns = [
# Home page
path('', views.index, name="index"),
# Page that shows all topics.
path('topics/', views.topics, name='topics'),
# Detail page for a single topic.
path('topics/<int:topic_id>/', views.topic, name='topic'),
# Page for adding a new topic,\
path('new_topic/', views.new_topic, name='new_topic'),
# Page for adding a new entry
path('new_entry/<int:topic_id>/', views.new_entry, name='new_entry'),
我尝试过一遍教科书中打印的每一行。一切看起来都不错。不明白为什么我会收到错误。我希望服务器将我带到 localhost:8000/new_topic
您正在
new_entry
中定义 new_topic
。小心空白。如果一个函数定义在另一个未缩进的函数定义下缩进,则缩进的定义是另一个函数作用域的一部分,并且不能在其他模块中导入。要解决此问题,请确保 def new_entry(...)
未缩进:
def new_topic(request):
"""Add a new topic"""
# new_topic logic here
def new_entry(request, topic_id):
"""Add a new entry for a particular topic."""
# new_entry logic here