Django:自定义ManyToManyField表单选项

时间:2017-08-04 11:50:53

标签: python django

我在Django模板中有一个ManyToManyField,如下所示:{{ form.contacts }}

在列表中呈现Contact个对象时,Django会为每个对象(ID)打印__str__(或__unicode__)。

就我而言,我希望对每个对象进行更人性化的显示,而不是渲染每个对象ID;我想拥有该对象的名称以及更多关于它的数据。

那么,有没有办法自定义每个列表项,以便我可以在HTML中添加div并显示每个对象的其他数据位,就像在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 for Contacts:

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)

1 个答案:

答案 0 :(得分:2)

  

那么,有没有办法自定义每个列表项,以便我可以在HTML中添加div并显示每个对象的其他数据位,就像在for循环中一样?

假设您的视图正在发送所有联系人的上下文变量,如下所示。

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 %}