我有一个Django应用程序,它是用来显示某些人的记录的。我不想为每个人的记录制作一个模板,而是想创建一个视图和一个模板,可以动态地显示不同人的记录。当我渲染包含个人信息的变量的模板时,我得到了这个错误:Could not parse the remainder: '('first_name',flat=True[0]'from'modelname.objects.values_list('first_name', flat=True)[0]'
我已经在几个不同的模型中存储了有关人员的信息,这些信息以列表的形式包含在records变量中。
views.py
def records(response, firstname):
#firstname is a variable containing the name entered into the url by the user
#the function will check if a record model with that first name is in records
#records is a list containing all record models
foundmodel = False
for i in range(len(records)):
firstname = firstname[0].upper() + firstname[1:] #Makes first letter uppercase
if firstname == records[i].objects.values_list('first_name', flat=True)[0]:
modelname = records[i]
#modelname will be passed to the template so the correct model can be referenced
foundmodel = True
break
else:
continue
#the loop will keep iterating until a match is found or there are no more record models to try
if foundmodel == True:
return render(response, 'base2.html', {'modelname':modelname})
#the template will be rendered with the information from the correct model if a model with the
#entered name is found
if foundmodel == False:
return HttpResponse('Person does not exist')
#if a model with the entered name is not found, this page will be rendered
相关的base2.html,如果找到具有所选名称的模型,则将呈现该文件
<div class="col-8-xs">
<img style="width:100px; height:100px;" alt="person's picture'" src="#">
<br>
<br>
<br>
<br>
<p>Full Name:{{modelname.objects.values_list('first_name', flat=True)[0]}} {{modelname.objects.values_list('last_name', flat=True)[0]}}</p>
<p>Age:{{modelname.objects.values_list('age', flat=True)[0]}}</p>
<p>Occupation:{{modelname.objects.values_list('occupation', flat=True)[0]}}</p>
</div>
urls.py
from django.urls import path
from app_3 import views
urlpatterns = [
path('home', views.homepage, name='homepage'),
path('base', views.base, name='base'),
path('<str:firstname>/records', views.records, name='records')
]
1条答案
按热度按时间xzv2uavs1#
您在模板中显示的逻辑,它属于视图。
解决方案1(推荐)
不知道为什么需要做所有的values_list(),但也许我错过了一些东西。假设你的modelname类有字段first_name,last_name,occupation,那么你需要做的就是:
溶液2
现在,* 如果您需要执行逻辑 *,请将其写入视图中,然后将其作为变量沿着,如下所示(但是,我不认为这是您需要或想要的):
然后按如下方式访问模板中的这些变量: