Accessing a field's verbose_name

41 views
Skip to first unread message

Déborah Leder

unread,
Aug 4, 2015, 7:31:38 AM8/4/15
to Django users
Hello

I have created models in a django application.

class FicheService(models.Model):

    id
= models.AutoField(primary_key=True)
    name
= models.CharField(max_length=64, verbose_name="Nom", blank=False)
    phone
= models.CharField(max_length=16, validators=[phone_verif], blank=True, null=True, verbose_name="N° de téléphone",
           
 help_text
="Le numéro de téléphone doit être entré dans le format:
'+999999999', jusqu'à 15 chiffres autorisés."
) # validators should be a
list

    site_web
= models.CharField(max_length=256, blank=True, null=True, verbose_name="Site web du service")
   
 commentaire
= models.CharField(max_length=128,
verbose_name
="Informations complémentaires", help_text="Facultatif",
blank
=True, null=True)

   
def __unicode__(self):
       
return self.name

   
def get_descr(self):
       
[...]

class Geomap(Page):

    services
= models.ManyToManyField(FicheService)



In the get_descr method, I would like to access the phone value (ex: +331234567), and the phone verbose_name ("N° de téléphone")...
The goal is to create a string to insert the description.

I have seen in multiple forums (including this google group : https://groups.google.com/forum/#!topic/django-users/ojaJMZ1YN-o) one answer which apparently worked for the people that asked the question, but it doesn't seem to work for me...

Here is the code I currently have for get_descr :
    def descr(self):
        my_string
= (
               
"<div class=\"info-title\">"
               
+ self.name
               
+ "</div>\n<div class=\"info-descr\">\n"
               
)
       
for curr_field in ("phone", "site_web", "commentaire"):
            curr_field_value
= getattr(self, curr_field) ;
            curr_field_name
= self._meta.get_field(curr_field).verbose_name ;
            my_string
= (
                    my_string
                   
+ "\n<br>\n"
                   
+ curr_field_name
                   
+ " : "
                   
+ curr_field_value
                   
)

        my_string
= my_string + "\n</div>"
       
return my_string



It doesn't display anything.
I have tested with the exact same code, whitout the line " + curr_field_name" and it displays the description how it should.

I also have tested to see what
self._meta.get_field("phone").verbose_name
returned, and it returns :
myapp.FicheService.phone


Does anyone have any idea about why it doesn't work for me ?

Déborah Leder

unread,
Aug 4, 2015, 8:11:51 AM8/4/15
to Django users

I am sorry, it seems like I've made a cuple of typos....

The name of my method is indeed get_descr all the time, so that is not the source of the problem.

And the command that I have tested and that returns myapp.FicheService.phone isn't
self._meta.get_field("phone").verbose_name
but
self._meta.get_field("phone")

To be more precise, it is even :
unicode(self._meta.get_field("phone"))
since without unicode, it returns the following error (see image) :

So, to sum up the lines of code and their effect :
self._meta.get_field("phone").verbose_name
and
unicode(self._meta.get_field("phone").verbose_name)
both cancel the display of my whole string without raising any error

self._meta.get_field("phone")
generates the error in the image

unicode(self._meta.get_field("phone"))
returns the string : "myapp.FicheService.phone"

Mike Dewhirst

unread,
Aug 4, 2015, 10:31:03 AM8/4/15
to django...@googlegroups.com
On 4/08/2015 10:11 PM, Déborah Leder wrote:
> <https://lh3.googleusercontent.com/-kYlAklxMo5A/VcCsAaABL4I/AAAAAAAAANs/-mNIE8is27A/s1600/error_verbose_name.PNG>
>
> I am sorry, it seems like I've made a cuple of typos....

This works for me ...

def get_verbose_name(obj, field):
"""New _meta API with Django 1.8"""
return
obj.__class__()._meta.get_field('{0}'.format(field)).verbose_name

So then you can call get_verbose_name with the instance of whatever
object you want plus the actual field name to get the verbose_name
declared in the model.

Mike
> -- 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...@googlegroups.com
> <mailto:django-users...@googlegroups.com>. To post to this
> group, send email to django...@googlegroups.com
> <mailto:django...@googlegroups.com>. Visit this group at
> http://groups.google.com/group/django-users. To view this discussion
> on the web visit
> https://groups.google.com/d/msgid/django-users/a46cb96d-c204-4d42-ab2b-06090a686490%40googlegroups.com
>
> <https://groups.google.com/d/msgid/django-users/a46cb96d-c204-4d42-ab2b-06090a686490%40googlegroups.com?utm_medium=email&utm_source=footer>.
>
>
For more options, visit https://groups.google.com/d/optout.

Déborah Leder

unread,
Aug 4, 2015, 10:53:40 AM8/4/15
to Django users
Thanks for your answer, Mike.

However, I have just tried it and it doesn't seem to work for me either...

Your code :
self.__class__()._meta.get_field('{0}'.format(field_name)).verbose_name
gives the exact same result as
self._meta.get_field(field_name).verbose_name

Mike Dewhirst

unread,
Aug 4, 2015, 7:44:02 PM8/4/15
to django...@googlegroups.com
Well that's a clue. The problem must be elsewhere. I think that API was
implemented in Django 1.7 because it works for me in 1.7

field_name is a string identical with the field name in the model. And
self must be an instance of the model with the field.

https://docs.djangoproject.com/en/1.8/ref/models/meta/#django.db.models.options.Options.get_field

> |
>
> --
> 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...@googlegroups.com
> <mailto:django-users...@googlegroups.com>.
> To post to this group, send email to django...@googlegroups.com
> <mailto:django...@googlegroups.com>.
> Visit this group at http://groups.google.com/group/django-users.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/6dff456a-6327-4b7c-a78c-47f36872b0d5%40googlegroups.com
> <https://groups.google.com/d/msgid/django-users/6dff456a-6327-4b7c-a78c-47f36872b0d5%40googlegroups.com?utm_medium=email&utm_source=footer>.

Déborah Leder

unread,
Aug 5, 2015, 5:31:29 AM8/5/15
to Django users
I read the django documentation, and I realised that both commands (  self.__class__()._meta.get_field('{0}'.format(field_name)) and self._meta.get_field(field_name) ) did return the right object, the problem was when I tried to access the verbose_name.
And after testing some more, I understood that it is because my verbose names have non ASCII caracters (for exemple, the verbose_name for phone is "N° de téléphone"), and that explains why it cancels the display of the whole string in which it is, and also why it doesn't raise an exception (because all the objects I want to access do exist).

So..it is a simple encoding problem...

Of course, in my models.py file was encoded with utf-8, but it wasn't enough.
I had to add an import :
from __future__ import unicode_literals

(see https://docs.djangoproject.com/en/1.8/ref/unicode/#general-string-handling)
Reply all
Reply to author
Forward
0 new messages