我想显示一个包含一组模型对象的表。
我的模特课:
from django.dbfrom django.db import models
from django.utils.translation import ugettext_lazy as _
class DamageKind(models.Model):
name = models.CharField(_('damage kind'), max_length=64)
regions = models.ManyToManyField(Region)
def __str__(self):
return self.name
class Meta:
verbose_name = _('damage kind')
verbose_name_plural = _('damage kinds')
我的表单类:
from django import forms
from crispy_forms.helper import FormHelper
from .models import DamageKind
class DamageKindList(forms.Form):
def __init__(self, *args, **kwargs):
self.damagekinds = kwargs.pop('damagekinds', [])
self.helper = FormHelper()
self.helper.form_method = 'post'
super().__init__(*args, **kwargs)
我的基本模板base.html:
<!DOCTYPE html>
<html>
<body>
{% block list %}
{% endblock %}
</body>
</html>
我的list_damagekinds.html:
{% extends "./base.html" %}
{% load crispy_forms_tags %}
{% block list %}
<form action="" method="post">
{% csrf_token %}
{{ damagekind_form }}
</form>
{% endblock %}
和我的views.py:
def list_damagekinds(request):
damagekinds = DamageKind.objects.all()
return render(
request,
'damage/list_damagekinds.html',
{'damagekind_form': DamageKindList(damagekinds=damagekinds), }
)
所以我的问题是如何通过不编辑来制作一个包含damagekinds所有名称的表格,所以只是展示这些。并使用使用crispy_forms FormHelper,而不是将其编码到模板中。
提前致谢。
答案 0 :(得分:0)
我的list_damagekinds.html
{% extends "./base.html" %}
{% load crispy_forms_tags %}
{% block list %}
<form action="" method="post">
{% csrf_token %}
<table>
{% for obj in damagekind_form %}
<tr> {{ obj.name }} </tr>
{% endfor %}
</table>
</form>
{% endblock %}