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:

views.py:

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


item_detail_view.html:

<div class="label">{{ form.name.label_tag }}</div><div class="value"> {{ item.name }}</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 django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/e84f2b57-6e64-4801-bd0f-ff8525e93ba1n%40googlegroups.com.

No comments:

Post a Comment