Ben S
Ben S

Reputation: 1467

Use variables when saving objects in Django

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

Upvotes: 3

Views: 952

Answers (2)

Sam Starling
Sam Starling

Reputation: 5378

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.

Upvotes: 3

Gabi Purcaru
Gabi Purcaru

Reputation: 31574

You can use the getattr function:

getattr(user, field_to_edit) = strip_tags(value)

Upvotes: 0

Related Questions