Reputation: 2335
This function as you can see updates a users field, where the field depends on the GET variable.
def update_p(request):
if request.method == "GET":
field = request.GET.get("field", "")
value = request.GET.get("value", "")
result = Users.objects.raw("SELECT id, %s FROM blog_users WHERE id = %s LIMIT 1", [field, request.session['user_id']])[0]
if result:
result = getattr(result, field)
result = value
result.save()
return HttpResponseRedirect("/blog/loggedin/profile/")
After
if result:
is where i am getting confused. I am getting the error
AttributeError: 'unicode' object has no attribute 'save'
I do not know why i am getting the error ,but hopefully its self-explanatory to you all. How can i prevent the error, or is there a better way to do this function?
Thanks for any help.
Upvotes: 0
Views: 38
Reputation: 1072
I think your string concatenation is incorrect
"SELECT id, %s FROM blog_users WHERE id = %s LIMIT 1", [field, request.session['user_id']]
should be
"SELECT id, %s FROM blog_users WHERE id = %s LIMIT 1", %(field, request.session['user_id'])
For example
>>> a = "SELECT id, %s FROM blog_users WHERE id = %s LIMIT 1", ["username", "ABC"]
>>> a
('SELECT id, %s FROM blog_users WHERE id = %s LIMIT 1', ['username', 'ABC'])
>>> a = "SELECT id, %s FROM blog_users WHERE id = %s LIMIT 1" %("username", "ABC")
>>> a
'SELECT id, username FROM blog_users WHERE id = ABC LIMIT 1'
also valid SQL would require the ABC to be in quotes "ABC"
Upvotes: 0
Reputation: 122376
By doing result = getattr(result, field)
you've turned result
into a 'unicode'
value instead of a User
object.
You probably meant to write:
if result:
setattr(result, field, value)
result.save()
Upvotes: 2