如何解决django 如何在视图中循环并在模板中打印
我的数据库中有序列号,每个序列号都有编码日期,我想从序列号中获取日期并打印在数据表中
我的view.py
from .models import Module
month = {'1': 'Jan','2': 'Feb','3': 'Mar','4': 'Apr','5': 'May','6': 'Jun','7': 'Jul','8': 'Aug','9': 'Sep','10': 'Oct','11': 'Nov','12': 'Dec'}
year = {'L': '2010','M': '2011','N': '2012','O': '2013','P': '2014','Q': '2015'}
@login_required()
def modules(request):
modules = Module.objects.all()
for module in modules:
day = module.serial_number[:2]
mon = module.serial_number[2:3]
mon = [val for key,val in month.items() if mon in key]
year1 = module.serial_number[3:4]
year1 = [val for key,val in year.items() if year1 in key]
print(module.serial_number,day,mon,year1)
total_modules = modules.count()
context = {'modules': modules,'total_modules': total_modules,}
return render(request,'modules/modules.html',context)
当print(module.serial_number,year1)
我得到了我想要的
044PGG01501S 04 ['Apr'] ['2014']
127QGG01501S 12 ['Jul'] ['2015']
但不能在模板中工作
任何想法
解决方法
我强烈建议不要在简单属性的情况下使用此类循环,使用 django 的“注释”功能或编写模型的属性,例如:day、mon、year1 都是可行的选项 - 比使用 forloop 更好.
注释:https://docs.djangoproject.com/en/3.1/topics/db/aggregation/ 写入属性:https://docs.djangoproject.com/en/3.1/topics/db/models/#model-methods
django 模板中的 Forloop: https://docs.djangoproject.com/en/3.1/ref/templates/builtins/#for
所以基本上在模板中你应该可以使用
{% for module in modules %}
{{module.serial_number}} {{module.day}} {{module.mon}} {{module.year1}}
您遇到的问题是您没有在 forloop 中创建对象的属性(如果您坚持使用这种方法),但您创建了通用变量,您应该使用 module.day 而不是 day,依此类推。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。