1

I am using ajax to send data into a django view with data coming in via request.POST. I am posting the model field that needs to be updated as well as the model value. I just need to know how to use the field name variable I extract from request.POST['field_name'] so I can set the field in the model. Here is my code.

field_name = request.POST["field_name"]
field_value = request.POST["field_value"]

member_id = get_member_session(request).id
try:
    member = Members.objects.get(id=member_id)
except:
    status="ERROR-USER-DOES-NOT-EXIST"
    return json_status(status)

try:
    member.field_name=field_value
    member.save()
    return json_status('OK')
except:
    status = "USER_SAVE_ERROR"
    return json_status(status)

member.field_name is obviously not right. Do I need to use eval(field_name) or something like that? I would prefer not to if possible.

Many thanks

Rich

Rich
  • 1,769
  • 3
  • 20
  • 30

1 Answers1

5

Use setattr, which allows you to set a variable attribute on an object:

try:
    member._meta.get_field(field_name)
except member.FieldDoesNotExist:
    # return something to indicate the field doesn't exist
    return json_status('USER_FIELD_ERROR')

setattr(member, field_name, field_value)
member.save()
return json_status('OK')

edit: I updated to use model._meta.get_field, as it's a better approach. Mentioned in this answer for another question.

Community
  • 1
  • 1
Alex Vidal
  • 4,080
  • 20
  • 23
  • Sorry to retract the green tick but I put the code in and get the following error: 'argument of type 'Members' is not iterable' on your 'if field_name in member:'. I can't see what it is. I have removed the 'if' statement and it works great but better not say completely right until I know the answer. Thanks again Alex – Rich Jan 04 '11 at 12:34