视图.py
def what(request):
user = request.user
report = Report.objects.get(user=user.id)
reportnotesform=ReportNotes(instance=report)
reportform = ReportForm(instance=report)
typeList = Types.objects.filter(user=user, is_active=True,parent_type_id=None)
list = []
for type in typeList:
if not type.parent_type_id:
list.append(type)
subtype = Types.objects.filter(parent_type_id=type.id, is_active=True)
for subtypes in subtype:
list.append(subtypes)
if request.method == 'POST':
ReportType.objects.filter(report=report).delete()
checked_ones = [unicode(x) for x in subtype if unicode(x) in request.POST.keys()]
reportnotesform=ReportNotes(request.POST,instance=report)
if reportnotesform.is_valid():
report=reportnotesform.save(commit=False)
report.user=request.user
report.save()
for entry in checked_ones:
r = ReportType()
r.report = report
r.title = entry
r.save()
return redirect('/member/where/')
checked_ones = [x.title for x in ReportType.objects.filter(report=report)]
return render(request, 'incident/what.html',
{
'newreport_menu': True,
'typeList':list,
'checked_ones':checked_ones,
# 'typelist': typelist,
'ReportNotes':reportnotesform,
'ReportForm':reportform
})
模型.py
class ReportType(models.Model):
report = models.ForeignKey(Report)
title = models.CharField('Incident Type', max_length=200)
模板
{% for type in typeList%}
{% if type.parent_type_id == None %}
<h1>{{type.title}}</h1>
{% else %}
<p><input type="checkbox">{{type.title}}</input></p>
{% endif %}
{% endfor %}
我正在使用模型表单动态显示复选框。
这是我从数据库中获取值并显示的视图。类型列表对象过滤的值需要显示值以及复选框。对于类型对象,没关系。在 django 中有什么方法可以做到这一点。