DEV Community

DoriDoro
DoriDoro

Posted on

How to get the `verbose_name` of an attribute of a model.

Introduction

Sometimes you need the verbose_name of an attribute of a model in a Django view. Perhaps you want to display the verbose_name in a template, or you want to create an entry (LogEntry), or whatever reason you may have.
You can't access the verbose_name in a Django template, so you need to retrieve the verbose_name in your view or create a template tag. The verbose_name can be used for logging, for sending messages, or for any other purpose.


I am going to show you how to get the verbose_name of the model attribute. In my example, I get the verbose_name of the model attribute when a user has filled in a form (UserProfileForm) and the form is valid.



# views.py

from django.views.generic.edit import UpdateView
from django.core.exceptions import FieldDoesNotExist
from django.urls import reverse_lazy
from .models import UserProfile
from .forms import UserProfileForm

class UserProfileUpdateView(UpdateView):
    model = UserProfile
    form_class = UserProfileForm
    template_name = 'userprofile_form.html'
    success_url = reverse_lazy('profile')

    def form_valid(self, form):
        description = {}

        if form.has_changed():
            for field in form.changed_data:
                try:
                    name = self.object._meta.get_field(field).verbose_name
                except FieldDoesNotExist:
                    name = form.fields[field].label

                description[name.capitalize()] = form.cleaned_data[field]

        print("Changed fields and new values:", description)

        return super().form_valid(form)


Enter fullscreen mode Exit fullscreen mode

Let's say the user has changed the first_name and last_name in the UserProfileForm.

What happens here, is:

  • we call the form_valid() method when the form is valid.
  • form.has_changed(): To determine whether the field value(s) has changed from its initial value, use the has_changed() method. It returns True or False.
  • form.changed_data: The changed_data attribute returns a list of the names of the fields whose values in the bound data of the form (usually request.POST) are different from what was provided in the initial. It returns an empty list if no data differs.


>>> form.changed_data
['first_name', 'last_name']


Enter fullscreen mode Exit fullscreen mode
  • name = self.object._meta.get_field(field).verbose_name: The name variable will hold the verbose_name of the modified attribute in UserModel. In our example, either first_name or last_name. This line is where the magic happens.
    • self.object: This object is the object that is updated
    • ._meta: The _meta is an API that allows other parts of the system such as lookups, queries, forms and the admin to understand the capabilities of each model.
    • .get_field(field_name): It returns the field instance of the given field_name.
    • .verbose_name: The verbose_name method returns the human readable name of the object/attribute stored in the model.

Summary:
We store the verbose_name in the variable: name.
We start with self.object, which is the object we want to modify. With ._meta we have access to the metadata of the model. The metadata contains everything that is not a field in the model. With the method get_field() we get the single field of the model. The verbose_name is stored in the metadata.


Django documentation links:

Top comments (0)