In Django, Using Form to get Field Labels in ListView and DetailView

I don’t know if this is good practice, but to get field labels in a ListView, DetailView, or DeleteView it seems to work fine if you just add a form to the context:

views.py:

class ItemDetailView(DetailView):
    model = Item 
    context_object_name = "item"

    def get_context_data(self, **kwargs):
        context_data = super().get_context_data(**kwargs)
        # just to get the labels
        context_data['form'] = ItemForm
        return context_data

item_detail_view.html:

<div class="label">{{ form.name.label_tag }}</div><div class="value">item.name</div>
<div class="label">{{ form.brand.label_tag }}</div><div class="value">item.brand</div>
<div class="label">{{ form.sn.label_tag }}</div><div class="value">item.sn</div>

You can use label instead of label_tag

This works fine with most fields but fails with ManyToMany fields. Still, it seems to be the easiest way to get most field labels without having to type them in.

Is this a great idea or am I missing some reason that this is bad?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.