3

In Django, is there a way to identify which attribute of an object I want to edit by using a POST/GET variable instead of explicitly naming it?

For example, I want to do this:

def edit_user_profile(request):
    field_to_edit = request.POST.get('id')
    value = request.POST.get('value')
    user = User.objects.get(pk=request.user.id)
    user.field_to_edit = strip_tags(value);
    user.save()

instead of this:

def edit_user_profile(request):
    value = request.POST.get('value')
    user = User.objects.get(pk=request.user.id)
    user.first_name = strip_tags(value);
    user.save()
1
  • 1
    There's no reason to write user = User.objects.get(pk=request.user.id) -- request.user is already a User object Commented Aug 27, 2011 at 17:52

2 Answers 2

3

Gabi's answer is exactly what you want. You could use setattr instead though:

setattr(user, field_to_edit, strip_tags(value))

Which is (very very slightly!) more intuitive.

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

Comments

0

You can use the getattr function:

getattr(user, field_to_edit) = strip_tags(value)

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.