django - 分配前引用的 /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)
有人可以解释一下这个错误以及如何解决它吗?
解决方案
您的型号名称是post
。而且您在函数中post
用作变量。post_detail
这就是你得到错误的原因。将您的变量名称从更改post
为另一个变量。我认为它会起作用。
推荐阅读
- python - 使用 Python -Pandas 在数据框中舍入小时数
- r - R管道工API - 安装的路由器不显示
- php - CodeIgniter 4,辅助功能不起作用
- python - 在 python 中,如何返回列表中的所有元组?
- jquery - Kendo UI:原始对象数组的源绑定
- ios - 如何在 Swift 中通过蓝牙获取附近的 iPhone 和 Android 设备列表?
- php - Mac OS Catalina:无法从 PHP 执行 ruby
- php - 在 php 上通过 shell_exec 运行 ffprobe 没有输出,但主要命令本身
- javascript - 将对象作为函数参数传递
- javascript - 从 Javascript/Node 中的异步数据创建 REST API