Olivier Pons
Olivier Pons

Reputation: 15778

Django: how to read a property of a model through a function?

I have my function like this:

def get_initial(self):
    initial = super(EditView, self).get_initial()
    u = self.request.user
    initial['user_last_name'] = u.last_name if u.last_name else u''
    initial['email'] = u.email if u.email else u''
    return initial

I will have a lot of fields to pre-fill so I'd like to do something like this (the following code doesnt work):

def get_initial(self):
    initial = super(EditView, self).get_initial()

    def apply_initial(idx, obj, prop):
        initial[idx] = obj[prop] if getattr(obj, prop) else u''

    u = self.request.user
    apply_initial('user_first_name', u, 'first_name')
    apply_initial('user_last_name', u, 'last_name')
    # ... and so on

I get:

'User' object has no attribute '__getitem__'

What am I missing to make it work?

Upvotes: 0

Views: 58

Answers (2)

knbk
knbk

Reputation: 53669

In your original code you look if u.last_name has an empty value, not whether it exists. A shorter version of that code would be:

def get_initial(self):
    initial = super(EditView, self).get_initial()
    u = self.request.user
    initial['user_last_name'] = u.last_name or u''
    initial['email'] = u.email or u''
    return initial

The or operator in Python does not just return a boolean, but instead returns the left-hand value if it is non-empty, and otherwise returns the right-hand value.

Upvotes: 0

Rohit Jain
Rohit Jain

Reputation: 213261

You're trying to access the prop as index of object. That should be getattr(obj, prop) instead of obj[prop]:

def apply_initial(idx, obj, prop):
    initial[idx] = getattr(obj, prop, u'')

Upvotes: 2

Related Questions