【发布时间】:2018-03-03 23:00:23
【问题描述】:
我在 Django 1.9 教程中使用 Django 2.0.2,但在重建我的 URL 后无法弄清楚问题出在哪里。错误显示(视图rango.views.category 没有返回一个HttpResponse 对象,而是返回了None。)
from django.template import RequestContext
from django.shortcuts import render_to_response
from rango.models import Category, Page
def index(request):
# Obtain the context from the HTTP request.
context = RequestContext(request)
# Query the database for a list of ALL categories currently stored.
# Order the categories by no. likes in descending order.
# Retrieve the top 5 only - or all if less than 5.
# Place the list in our context_dict dictionary which will be passed to the template engine.
# Query for categories - add the list to our context dictionary.
category_list = Category.objects.order_by('-likes')[:5]
context_dict = {'categories': category_list}
# looping through each category returned, and create a URL attribute.
# This attribute stores an encoded URL (e.g spaces replaced with underscores).
for category in category_list:
category.url = category.name.replace(' ', '_')
# Render the response and return to the client!
return render_to_response('rango/index.html', context_dict, context)
def category(request, category_name_url):
# Request our context from the request passed to us.
context = RequestContext(request)
# Change underscores in the category name to spaces.
# URLs don't handle spaces well, so we encode them as underscores.
# We can then simply replace the underscores with spaces again to get the name.
category_name = category_name_url.replace('_', ' ')
# Create a context dictionary which we can pass to the template rendering engine.
# We start by containing the name of the category passed by the user.
context_dict = {'category_name': category_name}
try:
# Can we find a category with the given name?
# If we can't, the .get() method raises a DoesNotExist exception.
# So the .get() method returns one model instance or raises an exception.
category = Category.objects.get(name=category_name)
# Retrieve all of the associated pages.
# Note that filter returns >= 1 model instance.
pages = Page.objects.filter(category=category)
# Adds our results list to the template context under name pages.
context_dict['pages'] = pages
# We also add the category object from the database to the context dictionary.
# We'll use this in the template to verify that the category exists.
context_dict['category'] = category
except Category.DoesNotExist:
# We get here if we didn't find the specified category.
# Don't do anything - the template displays the "no category" message for us.
pass
# Go render the response and return it to the client.
return render_to_response('rango/category.html', context_dict, context)
urls.py:
from django.urls import path, re_path
from . import views
urlpatterns = [
path('', views.index, name='index'),
re_path(r'^category/(?P<category_name_url>\w+)/$', views.category, name='category'),
]
【问题讨论】:
-
您在
try中缺少返回。 -
非常感谢您的贡献...问题已解决