python - 赋值前引用的局部变量“all_inf”
问题描述
我是 django 的新手。所以我正在尝试使用 Django 创建一个 CRUD 应用程序,但是我在尝试构建它时收到“分配前引用的局部变量‘all_inf’”这个错误
这是我的观点.py
- - 编码:utf-8 - -
从未来导入 unicode_literals
从 django.shortcuts 导入渲染 从 .forms 导入创建 从注册.模型导入用户
在此处创建您的视图。
def add_show(请求):
if request.method == 'POST':
crt = Create(request.POST)
if crt.is_valid():
username = crt.cleaned_data['name']
useremail = crt.cleaned_data['email']
user_contact = crt.cleaned_data['contact_number']
save_to_db = User(name=username, email=useremail,
contact_number=user_contact)
save_to_db.save()
crt = Create()
else:
crt = Create()
all_inf = User.object.all()
return render(request, 'index.html', {'form': crt, 'info': all_inf})
我也试图从数据库中获取数据并在表中显示所有数据但它没有显示:(
这是我的示例代码:
div class="col-sm-8">
<h4 class="text-center alrt alert-info">Showing all results</h4>
{% if all_inf %}
<h4>Table Data</h4>
<table class="table table-dark">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">Name</th>
<th scope="col">Email</th>
<th scope="col">Contact Number</th>
<th scope="col">Actions</th>
</tr>
</thead>
<tbody>
{% for inf in info %}
<tr>
<td>{{inf.id}}dfdf</th>
<td>{{inf.name}}</td>
<td>{{inf.email}}}</td>
<td>{{inf.contact_number}}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<h4 class="btn btn-danger">No Records Found Try again</h4>
{% endif%}
</div>
</div>
解决方案
这是因为从句all_inf
中没有。if
但是,在所有情况下都会执行 return 语句。
all_inf
Soln -在外部if else
块之前放置一些默认值。
要么更改返回语句
if request.method == 'POST':
crt = Create(request.POST)
if crt.is_valid():
username = crt.cleaned_data['name']
useremail = crt.cleaned_data['email']
user_contact = crt.cleaned_data['contact_number']
save_to_db = User(name=username, email=useremail,
contact_number=user_contact)
save_to_db.save()
crt = Create()
return render(request, 'index.html', {'form': crt}) #this is not having the ```all_inf```
else:
crt = Create()
all_inf = User.object.all()
return render(request, 'index.html', {'form': crt, 'info': all_inf})
或保持代码相同并根据您的模板代码定义all_inf
asNone
或空列表([])
all_inf = None
if request.method == 'POST':
crt = Create(request.POST)
if crt.is_valid():
username = crt.cleaned_data['name']
useremail = crt.cleaned_data['email']
user_contact = crt.cleaned_data['contact_number']
save_to_db = User(name=username, email=useremail,
contact_number=user_contact)
save_to_db.save()
crt = Create()
else:
crt = Create()
all_inf = User.object.all()
return render(request, 'index.html', {'form': crt, 'info': all_inf})
推荐阅读
- python - 一个类的对象是否有可能与它们所在的类属性具有相同的引用?
- python - 在另一个数据库中重新创建对象的可用 SQLAlchemy 方法有哪些?
- flutter - 如何在 Flutter 中将特定的 String 格式转换为 DateTime?
- greasemonkey - Grasemonkey 用户脚本在“for”循环后停止执行
- laravel - Spatie 媒体库 - 无法加载资源 404(未找到)
- nginx - 确保所有 http 请求都通过我的 nginx api 网关
- flutter - 在颤振中初始化 AnimationController 时出错
- python - 气流单元测试
- extjs - 如何在 EXTJS 中获取 MAIN 控制器的引用?
- vue.js - 缺少 slug 学习 vue.js