Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
like image 517
Ben S Avatar asked Dec 04 '25 01:12

Ben S


1 Answers

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.

like image 110
Sam Starling Avatar answered Dec 06 '25 16:12

Sam Starling