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开发者_StackOverflow中文版(value);
user.save()
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.
You can use the getattr
function:
getattr(user, field_to_edit) = strip_tags(value)
精彩评论