Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Django getattr(): attribute name must be string

Tags:

python

django

I am using python, Django and get the following error:

getattr(): attribute name must be string

location: val = getattr(obj, field)

        if field in headers:
            if not isinstance(field, str):
                val = getattr(obj, field)
            else:
                val = getattr(obj, field.LastName)

            if callable(val):
                val = val()
            if type(val) == unicode:
                val = val.encode("utf-8")
            row.append(val)

I have tried many variation of code but all failed.

like image 691
Abhishek Avatar asked Jan 24 '26 04:01

Abhishek


1 Answers

You can confirm the object type of field by using print(type(field)). It will likely not be a string considering the error.

Looking at your code, it looks like field will be an object with attributes that are strings, such as LastName. The line

val = getattr(obj, field)

would probably be better off reading

val = getattr(obj, field.someattribute)

If field.someattribute is not a string, you can cast it to string using str(field.someattribute)

For a grand total of val = getattr(obj, str(field.someattribute))

like image 109
Naltroc Avatar answered Jan 26 '26 18:01

Naltroc