[Answered ]-Access model name in Django CreateView from template

2👍

  1. The name of your first view should be different, e.g. KanriCreateView
  2. It might help you to get the name of the view class: {{ view.class.name }}
  3. If you have access to the view class (which is provided by default by the ContextDataMixin) you can access the model attribute of the view class and get the name of the model: {{ view.model.__name__ }}

Cheers

0👍

If you’re using a ModelForm for your CreateView, this doesn’t quite work. This is because you’re not specifying

model = MyModel

but instead you’re specifying

form_class = MyModelForm

so what you can do instead is

from django.contrib.admin.utils import model_ngettext

model_ngettext(self.form_class._meta.model, 1)
👤Ben

0👍

I propose a solution updated for Django 2 and 3: retrieve the model verbose name from the ModelForm associated to the CreateView.

class YourCreateView(CreateView):

    form_class = YourModelForm

    def get_context_data(self, **kwargs):
        """Add the models verbose name to the context dictionary."""

        kwargs.update({
            "verbose_name": self.form_class._meta.model._meta.verbose_name,})
        return super().get_context_data(**kwargs)

Now you can use {{ verbose_name }} inside your template.

Please, remark the double _meta in the code snippet above: the first is meant to access the model from the ModelForm, while the second accesses the verbose name of the Model.

As with internationalization, remark that if your model uses ugettext as shown below, then the verbose name will automatically be translated in the template.

from django.utils.translation import ugettext_lazy as _

class MyModel(models.Model):
    class Meta:
        verbose_name = _("your verbose name")

Leave a comment