Sunday, September 19, 2021

Using ModelForm to get labels in a DetailView

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

class ItemDetailView(DetailView):

    model = Item
    context_object_name = "item"

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


<div class="label">{{ }}</div><div class="value"> {{ }}</div>
<div class="label">{{ form.notes.label_tag }}</div><div class="value"> {{ item.notes }}</div>
<div class="label">{{ form.asset_number.label_tag }}</div><div class="value"> {{ item.asset_number }}</div>
<div class="label">{{ form.serial_number.label_tag }}</div><div class="value"> {{ item.serial_number }}</div>
<div class="label">{{ form.network_name.label_tag }}</div><div class="value"> {{ item.network_name }}</div>

You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to
To view this discussion on the web visit

No comments:

Post a Comment