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')
Justin Andrew
  • 242
  • 1
  • 10
  • 2
    google `setattr`, `getattr`... and you shall find the answer. – sberry Nov 26 '13 at 01:06
  • 2
    Style tip: It is considered a bad practice to do: `if not element in form.errors:`. As shown [here](http://stackoverflow.com/questions/2710940/python-if-x-is-not-none-or-if-not-x-is-none), it should be: `if element not in form.errors:` (I know the link talks about `is`, but the same rule applies to `in`). –  Nov 26 '13 at 01: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](http://nedbatchelder.com/blog/201112/keep_data_out_of_your_variable_names.html) and [this one](http://stupidpythonideas.blogspot.com/2013/05/why-you-dont-want-to-dynamically-create.html) for more details. – abarnert Nov 26 '13 at 02: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. – abarnert Nov 26 '13 at 02:31

1 Answers1

2

Use setattr like so:

setattr(u, element, form.cleaned_data[element])
sberry
  • 128,281
  • 18
  • 138
  • 165
  • 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. – Justin Andrew Nov 26 '13 at 01:14