我正在使用Django建立新网站,并希望从中获取对象名称
sql。但它保持输出错误对象.get匹配查询不存在
我需要在哪里修改代码?
意见
def predict1(request):
name = ''
loginstatus = False
try:
name = request.session['name']
loginstatus = True
except:
return HttpResponseRedirect('/login/?back=未來型預測')
category_id = FutureMember.objects.get(member_name=name).type
cname = FutureFqType.objects.get(type_id=category_id).type_name
return render_to_response('predicts.html', {'cname': cname,'loginstatus': loginstatus, 'name': name})
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<div><h2>根據投資人屬性測驗結果,您屬於<font color="#75CA20">{{ cname }} 您好! {{ name }}</font></h2>
<form action="/predict/" method="post">
</div>
</body>
</html>
楷模
class FutureFqType(models.Model):
type_id = models.CharField(primary_key=True, max_length=2)
type_name = models.CharField(max_length=20)
type_describe = models.TextField(blank=True, null=True)
type_score = models.CharField(max_length=20)
class Meta:
managed = False
db_table = 'future_fq_type'
我希望{{cname}}的输出是数据,但实际无法输出
出现错误FutureFqType匹配查询不存在。
新观点
from django.shortcuts import get_object_or_404
def predict1(request):
loginstatus = False
try:
name = request.session["name"]
loginstatus = True
except KeyError:
return HttpResponseRedirect("/login/?back=未來型預測")
category_id = get_object_or_404(FutureMember, member_name=name).type
cname = get_object_or_404(FutureFqType, type_id=category_id).type_name
return render_to_response(
"predicts.html",
{"cname": cname, "loginstatus": loginstatus, "name": name},
)
页面输出
enter image description here
最佳答案
from django.shortcuts import HttpResponse, get_object_or_404, redirect, render
def predict1(request):
loginstatus = False
try:
name = request.session["name"]
loginstatus = True
except KeyError:
return redirect("/login/?back=未來型預測")
try:
member = FutureMember.objects.get(member_name=name)
except FutureMember.DoesNotExist:
msg = f"<h1>FutureMember not found with member_name=`{name}`</h1>"
return HttpResponse(msg)
try:
fqtype = FutureFqType.objects.get(type_id=member.type)
except FutureFqType.DoesNotExist:
msg = f"<h1>FutureFqType not found with type_id=`{member.type}`</h1>"
return HttpResponse(msg)
else:
cname = fqtype.type_name
data = {"cname": cname, "loginstatus": loginstatus, "name": name}
return render("predicts.html", data)