首页 > 解决方案 > 分配前引用的 /detail/1/ 局部变量“post”处的 UnboundLocalError

问题描述

我在 Django 中收到以下错误:

UnboundLocalError at /detail/1/
local variable 'post' referenced before assignment
Request Method: GET
Request URL:    http://127.0.0.1:8000/detail/1/
Django Version: 2.2.1

这是产生错误的地方:

from django.shortcuts import render, get_object_or_404
from .models import post

def home (request) :
    context = {
        'titel': 'homepage',
        'posts': post.objects.all()
    }
    return render (request, 'site.html', context) 


def post_detail(request, post_id):
    post = get_object_or_404(post,id=post_id)
    context = {
        'title': post,
        'post': post,
    }

    return render(request, 'details.html', context)

有人可以解释一下这个错误以及如何解决它吗?

标签: django

解决方案


您的型号名称是post。而且您在函数中post用作变量。post_detail这就是你得到错误的原因。将您的变量名称从更改post为另一个变量。我认为它会起作用。


推荐阅读