我在 Django 模板中有一个 ManyToManyField,如下所示:{{ form.contacts }}
在列表中呈现 Contact
对象时,Django 会打印每个对象的 __str__
(或 __unicode__
)(ID)。
就我而言,我希望以更人性化的方式显示每个对象,因此不必渲染每个对象的 ID;我想要该对象的名称以及有关它的更多数据。
那么,有什么方法可以自定义每个列表项,以便我可以将 div 添加到 HTML 并显示每个对象的其他数据位,就像在 for 循环中所做的那样?
Django 渲染:
<li>
<label for ...>
<input type='checkbox'...>
</input>
'id generated here'
</label>
</li>
我想要什么:
<li>
<label for ...>
<input type='checkbox'...>
</input>
<div class='wrapper'>
<h3>'contact name here'</h3>
<h4>'contact id here'</h4>
<h4>'contact created date here'</h4>
</div>
# Note that the only difference is the markup here, where I can add in my own tags, as opposed to the ID/slug string that Django rendered
</label>
</li>
更新
联系人的 models.py:
class Contact(models.Model):
parent = models.ManyToManyField(CompanyModel, related_name='contact',
verbose_name='Parent Company')
cl_name = models.CharField(max_length=40, verbose_name='Name')
cl_dt_created = models.DateTimeField(auto_now_add=True, verbose_name='Date Created')
cl_slug = models.SlugField()
class Meta:
verbose_name = 'Contact'
def __unicode__(self):
return self.cl_slug
def __str__(self):
return self.cl_slug
def get_absolute_url(self):
return reverse('contact-detail', kwargs={'cl_slug': self.cl_slug, 'company': self.parent.company})
def save(self, *args, **kwargs):
slug_create(self) # Call slug_save method
super(Contact, self).save(*args, **kwargs)
最佳答案
So, is there any way to customize each of the list items so that I can add divs to the HTML and display other bits of data for each object like you would do in a for loop?
假设您的 View 正在发送所有联系人的上下文变量,如下所示。
def myview(request, *a, **kw):
# querying the related objects
company_model = CompanyModel.objects.get(id=some_id)
# creating a dictionary containing the queryset that we want based on these related objects.
data['contacts'] = Contacts.objects.filter(parent__id=company_model.id)
# You can still pass your form in with this data like so
data['form'] = MyForm
# passing that queryset and the form to the template to be displayed.
return render(request, "path/to/template", data)
您应该能够像这样在模板中迭代该查询集。
# this would go inside your form
{% for contact in contacts %}
<div>{{ contact.cl_name }}</div>
<div>{{ contact.cl_slug }}</div> cl_dt_created
<div>{{ contact.cl_dt_created }}</div>
<input type="checkbox" value="{{ contact.id }}" name="contact" />
{% endfor %}
关于python - Django:自定义ManyToManyField表单选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45506119/