0

我可能很愚蠢地尝试在新发布的 Django 2.0 上使用 Django 1.9 完成 Tango。我到了第 6 章,并收到以下错误。

在此处输入图像描述

该错误与我的views.py文件(如下)有关,其中包含以下内容,

context_dict['pages'] = pages
context_dict['category'] = category

似乎是罪魁祸首。在 Django 2.0 中将变量分配给字典的方式是否发生了变化,或者这是一个 Python 问题?可以提供来自所有其他应用程序文件的代码。

视图.py

from django.shortcuts import render
from rango.models import Category, Page

def index(request):

    category_list = Category.objects.order_by('-likes')[:5]
    context_dict = {'categories':category_list}
    return render(request, 'rango/index.html', context=context_dict)

def about(request):
    return render(request, 'rango/about.html')

def show_category(request, category_name_slug):
    context_dict = []

    try:

        category = Category.objects.get(slug=category_name_slug)

        pages = Page.objects.filter(category=category)

        context_dict['pages'] = pages
        context_dict['category'] = category

    except Category.DoesNotExist:
        context_dict['category'] = None
        context_dict['pages'] = None

    return render(request, 'rango/category.html', context_dict)

模型.py

from django.db import models
from django.contrib import admin
from django.template.defaultfilters import slugify

# Create your models here.

class Category(models.Model):
    name = models.CharField(max_length=128, unique=True)
    views = models.IntegerField(default=0)
    likes = models.IntegerField(default=0)
    slug = models.SlugField(unique=True)

    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        super(Category,self).save(*args, **kwargs)

    class Meta:
        verbose_name_plural = 'Categories'

    def __str__(self):
        return self.name


class Page(models.Model):
    category = models.ForeignKey(Category, on_delete=models.PROTECT)
    title = models.CharField(max_length=128)
    url = models.URLField()
    views = models.IntegerField(default=0)
    def __str__(self): # For Python 2, use __unicode__ too
    return self.title

class PageAdmin(admin.ModelAdmin):
    list_display = ('title','category','url')

页面(来自管理页面) 页面(来自管理页面)

4

1 回答 1

1

你的问题在这里:

def show_category(request, category_name_slug):
    context_dict = []

wherecontext_dict应该是字典,而不是列表:

def show_category(request, category_name_slug):
    context_dict = {}
    #also valid: context_dict = dict()
于 2018-02-06T17:23:27.450 回答