0

I am trying to loop through a list of known elements so I can check if they were submitted properly, then do something with them. Problem is, my elements are strings, but the corresponding element object is needed to assign a value to a user object.

Should something else be where eval(element) is?

elements = ('first_name', 'last_name', 'email')

u = request.user

for element in elements:    
    if not element in form.errors:
        dajax.alert('alert: %s' % form.cleaned_data[element])
        u.eval(element) = form.cleaned_data[element]
        dajax.add_css_class('div #%s' % element , 'form-group has-success')
4
  • 2
    google setattr, getattr... and you shall find the answer. Commented Nov 26, 2013 at 1:06
  • 2
    Style tip: It is considered a bad practice to do: if not element in form.errors:. As shown here, it should be: if element not in form.errors: (I know the link talks about is, but the same rule applies to in). Commented Nov 26, 2013 at 1:08
  • Are you sure you want to do this? If your object had a single dict attribute with keys 'first_name', 'last_name', and 'email' instead of three separate attributes, you wouldn't need a fancy setattr(thingy, element, value) fancy, just thingy.elements[element] = value. See this blog post and this one for more details. Commented Nov 26, 2013 at 2:31
  • Of course if you're using these attributes as statically-named attributes in most of your code, and only need to access them dynamically in one place, then this is a reasonable way to do it. It's just that when you usually want to access them dynamically, you probably didn't want attributes. Commented Nov 26, 2013 at 2:31

1 Answer 1

2

Use setattr like so:

setattr(u, element, form.cleaned_data[element])
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks sberry. For others just learning python's built in functions, note that you may not: getattr(u, element) = form.cleaned_data[element] Use the setattr() as sberry shows above.

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.