python - 如何从 mysql 中检索数据并使用 django 将其显示在视图中
问题描述
这是我的模型:
from django.db import models
# Create your models here.
class Contact(models.Model):
name = models.CharField(max_length=125, null=True)
email = models.EmailField()
address = models.CharField(max_length=255)
city = models.CharField(max_length=150)
zipcode = models.CharField(max_length=15)
我正在尝试在视图中显示数据:
<div class="row d-block">
<table class="table table-responsive">
<thead>
<tr>
<th>Name:</th>
<th>Email:</th>
<th>Address:</th>
<th>City:</th>
<th>Zipcode:</th>
</tr>
</thead>
<tbody>
{% for row in rows%}
<tr>
<th>{{rows.name}}</th>
<th>{{rows.emai}}</th>
<th>{{rows.address}}</th>
<th>{{rows.city}}</th>
<th>{{rows.zipcode}}</th>
</tr>
{%endfor%}
</tbody>
</table>
这是我在数据库中发送数据的函数。我的下一步是从 db 中检索数据并将其显示在 html 中:
from django.shortcuts import render
from django.http import HttpResponse
from pages.models import Contact
# from django.views import View
# Create your views here.
def home(request):
return render(request, 'index.html', {'title':'Home Page'})
def contact(request):
if(request.method == 'POST'):
data = Contact(
name = request.POST['name'],
email = request.POST['email'],
address = request.POST['address'],
city = request.POST['city'],
zipcode = request.POST['zipcode'],
)
data.save()
dbdata = Contact.objects.all()
print(dbdata)
return render(request, 'contact.html', {'title':'Contact Page','row':dbdata})
当我尝试从 db 中检索数据时,出现以下错误:
UnboundLocalError at /pages/contact/
local variable 'dbdata' referenced before assignment
如何检索和显示我的数据?
解决方案
传递上下文时出错..您在上下文中使用键行。但是您在 for loop.change 键行中调用行。将键行更改为行。并保持原样循环。
这里改变了传递上下文字典键
return render(request, 'contact.html', {'title':'Contact Page','rows':dbdata})
请让我知道它是否有效..
推荐阅读
- npm - Keen Bootstrap 高级模板的 npm 构建错误
- python - Flask 应用程序随机抛出内部服务器错误
- google-chrome - Chrome 不渲染 svg 图像
- keycloak - 负载均衡器级别的 Keycloak 身份验证
- python - 当我在 Python3.7 上运行下拉列表程序时,Kivy 立即崩溃
- android - 如何设置 shadow-cljs 以使用 Cordova + Clojurescript 重新加载代码?
- powershell - 尝试从根证书创建子证书时,Powershell -Signer 命令不起作用
- angular - Angular 组件看不到同一文件中的接口
- c++ - 为什么 C++ 中 set::end 的迭代器取消对集合中元素数量的引用?
- python - 如何在内部使用多处理时通过 API 重新启动烧瓶服务器