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()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With