3

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.

2
  • The error message is telling you the attribute name must be a string, and you are specifically calling getattr(obj, field) after testing that field is not a string. What did you expect to happen? Commented Jul 13, 2013 at 20:13
  • @BrenBarn field is a string, I have also used val = getattr(obj, "LastName") but that's also not working. As I've just started learning python I'm a naive in it. I could also upload my entire function if that doesn't flaws stackoverflow's policy... Commented Jul 13, 2013 at 20:18

2 Answers 2

5

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))

Sign up to request clarification or add additional context in comments.

Comments

5

May be you are missing the attribute name.

I was getting the same error for this

price = models.DecimalField(15, 2,)

but when I modified the code like below error was resolved.

price = models.DecimalField(max_digits=15, decimal_places=2,)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.