django hacks: accesing a model.field verbose_name...
July 2010
Sun Mon Tue Wed Thu Fri Sat
        1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
About
This site is an effort to share some of the base knowledge I have gathered through all this years working with Linux, FreeBSD, OpenBSD, Python or Zope, among others. So, take a look around and I hope you will find the contents useful.
Recent Entries
Recent Comments

collective.solr 1.0rc1 (Release candidate)
2010-07-30 plone.org releases

Products.cron4plone 1.1.5rc1 (Release candidate)
2010-07-30 plone.org releases

vs.dashboardmanager 0.2.6.1
2010-07-30 plone.org releases

Heads up! OpenBSD now supports multi-byte characters!
2010-07-30 OpenBSD Journal (undeadly.org)

Setting the Focus Distance on the Epson V700 Scanner
2010-07-29 betabug

Gnome Census Released (and Red Hat 16% vs Canonical 1% Flame)
2010-07-29 Ramble on

Cómo conectarse a bases de datos SQLite desde NetBeans
2010-07-29 vaites (dmnet)

Diferencias cambiando de Perl a Python
2010-07-28 blackshell

Monos y cacahuetes
2010-07-28 userlinux.net

No Gazoline
2010-07-28 betabug

[c2k10] (Part 5)
2010-07-28 OpenBSD Journal (undeadly.org)

Cómo evitar fbc_channel=1 con Facebook Fan/Like Box
2010-07-28 vaites (dmnet)

Copyright Nonsense
2010-07-28 Ramble on

New Plone Usergroup in Charlottesville, VA kicks off July 29th
2010-07-28 plone.org news

Redimensionar la ventana de Firefox sin extensiones
2010-07-27 vaites (dmnet)

ἀφορισμός XII: Silencio
2010-07-27 emereci

New committer: Baptiste Daroussin (ports)
2010-07-27 FreeBSD latest news

[c2k10] The Hackathon BBQ (Part 4) - June 25 - July 3, 2010, Edmonton, Alberta, Canada
2010-07-26 OpenBSD Journal (undeadly.org)

Setting up Bacula
2010-07-26 Evilcoder

Plone 4 upgrade coming to plone.org
2010-07-25 plone.org news

So I bought a Scanner
2010-07-24 betabug

FreeBSD 8.1 RELEASED
2010-07-24 Evilcoder

FreeBSD 8.1-RELEASE Available
2010-07-23 FreeBSD latest news

Announcing Tornado 1.0
2010-07-23 Ramble on

Sauna Sprint just around the corner
2010-07-22 plone.org news

April-June, 2010 Status Report
2010-07-22 FreeBSD latest news

O culeiro
2010-07-21 emereci

Limitando usuarios ssh en Mercurial
2010-07-21 userlinux.net

The Wire
2010-07-20 emereci

Comienza la mudanza, nos vamos a Reading
2010-07-18 blackshell

Recent Trackbacks
Categories
OpenBSD (8 items)
BSD (0 items)
FreeBSD (12 items)
Linux (2 items)
Security (3 items)
Python (18 items)
Zope (13 items)
Daily (120 items)
e-shell (8 items)
Hacks (7 items)
PostgreSQL (3 items)
OSX (7 items)
Nintendo DS (0 items)
enlightenment (0 items)
Apache (3 items)
Nintendo Wii (0 items)
Django (23 items)
Music (9 items)
Plone (7 items)
Varnish (0 items)
Lugo (1 items)
Sendmail (-1 items)
europython (7 items)
Archives

Syndicate this site (XML)

RSS/RDF 0.91

08 mayo
2008

django hacks: accesing a model.field verbose_name...

...directly within a view.

My first django hack, imagine you have a model like:

class Project(models.Model):

    """ A sample django model """

    name = models.CharField('Project name', max_length=250)
    start_date = models.DateField('Project started on')
    employee = models.CharField('Project associated to', max_length=250)

    def __unicode__(self):
        return self.name

    class Admin:
        list_display = ('name', 'start_date', 'employee')
        list_filter = ['employee']
        search_fields = ['name']

    class Meta:
        ordering = ['-start_date']
        verbose_name_plural = 'Projects';

Once we have our model, we can play with it through a python shell. In order to do that, we have to use the shell command of manage.py:

snowball:SomeProject wu$ python manage.py shell

This way, all the neccesary deps from django will be pre-loaded and we will end in a python console running inside our project environment. Then, we can do something like:

Python 2.5.2 (r252:60911, Apr 29 2008, 23:50:14)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from SomeProject.iapm.models import Project
>>> p = Project.objects.all()[0]
>>> p
<Project: francisco_2008_03>
>>>

Here, I've imported the Project model, which is a class, then I created an instance of that class getting some data from the database (the first entry in the projects list) and using such data to populate the attributes of the model's class (name, start_date and employee).

Next, I called the instance itself, which will call the __unicode__ method, which will return a unicode object contaning the project name.

Of course, I could check the different attributes of the instance, like the name:

>>> p.name
u'francisco_2008_03'

or the employee:

>>> p.employee
u'Wu'

With that, I got the value for each attribute but, what if I would like to show something like:

Atribute: value

Each field object have two attributes, name and verbose_name, that will show the name of the field when called. The problem appeared when I tried to access those attributes directly:

>>> p.employee.name
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'unicode' object has no attribute 'name'
>>> p.employee.verbose_name
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'unicode' object has no attribute   'verbose_name'
>>>

What happened here? Well, it is pretty easy to understand. When I called p.responsable what I got in return is an unicode object, which doesn't have nor a name attribute, neither a verbose_name attribute.

Well, thnx to theju in the #django irc channel (irc.freenode.net) I found a workaround:

>>> p._meta.get_field('responsable').verbose_name
'Responsable de proyecto'

Here, I called the get_field method to get a field object, which does have a verbose_name attribute. Easy, isn't it?

So I finally got something like:

>>> print p._meta.get_field('employee').verbose_name + ': ' + p.employee
Project associated to: Wu

Of course that could be used inside a view to, for example, create a list of empty attributes from a given model.

Posted by wu at 16:54 | Comments (0) | Trackbacks (0)
<< OpenBSD 4.3 released | Main | Diagnostic-Code: SMTP; 571 Denied by policy >>
Comments
Re: django hacks: accesing a model.field verbose_name...

This does not work inside of a template (e.g. as headers or labels for object data):

"Variables and attributes may not begin with underscores: 'object._meta.get_field"

Any ideas?!

Posted by: Derek at febrero 22,2010 19:09
Re: django hacks: accesing a model.field verbose_name...

Hi Derek. Yes, django template system does not allow you to access methods beginning with _, which in the end should be "private" in python (so I think it is good it doesn't). Perhaps the quickest solution would be to create a template filter, that given that object, returns the info, something like:


def get_object_field(object):
return object._meta.getfield # put here whatever you would like to return
get_object_field = register.filter(get_object_field)


Then, within the template, you could do something like:


{{ object|get_object_field }}


(Of course you will have to create your own filters module, take a look here to know how: http://docs.djangoproject.com/en/dev/howto/custom-template-tags/)

Hope that helps!

Posted by: Wu at febrero 24,2010 09:10
Re: django hacks: accesing a model.field verbose_name...

Thanks for this tip - it answered my question exactly!

Posted by: Ash at marzo 04,2010 05:17
Trackbacks
Please send trackback to:http://blog.e-shell.org/66/tbping
There are no trackbacks.
Post a comment