Home > other >  How to overcome error: 'ManyToOneRel' object has no attribute 'verbose_name' in
How to overcome error: 'ManyToOneRel' object has no attribute 'verbose_name' in

Time:11-29

In my app I have the following models:

class Category(BaseStampModel):
    cat_id = models.AutoField(primary_key=True, verbose_name='Cat Id')
    category = models.CharField(max_length=55, verbose_name='Category')

class MasterList(BaseStampModel):
    master_list_id = models.AutoField(primary_key=True, verbose_name='Master List Id')
    mast_list_category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True, verbose_name='Category')
    # Other fields ...

My BaseModel looks like this:

class BaseStampModel(models.Model):
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='%(class)s_created', blank=True, null=True, on_delete=models.SET_NULL, verbose_name='Created by')
    created_on = models.DateTimeField(auto_now_add = True, null=True, blank=True)

With this I am able to display the model objects and create/update instances.

In my view, when I want to retrieve the verbose_name from model "Category" using:

`model_fields = [(f.verbose_name, f.name) for f in Category._meta.get_fields()]`

I am getting the following error in my browser:

AttributeError: 'ManyToOneRel' object has no attribute 'verbose_name'

If I remove the the FK relationship from the field mast_list_category (make it a simple CharField) I don't get the error.

Gone through millions of pages, but no solution yet.

Any help is much appreciated.

CodePudding user response:

You can't access the verbose_name just like accessing model fields

But there are different ways of getting verbose_name. The better way is using get_field

model._meta.get_field('field_name').verbose_name

In your case, replace the model with Category and field_name with the field you want to get the verbose_name

CodePudding user response:

This is what I am doing:

Declare an empty array, loop through the model, get the field name and its verbose_name and append.

array_model_with_ver_name = []
for f in Category._meta.get_fields():
    if hasattr(f, 'verbose_name'):
        array_model_with_ver_name.append((f.verbose_name, f.name))
  • Related