1

在 django 应用程序中,我正在获取用户提交的表单数据,这些数据试图插入 mysql db,但即使 request.keys 与 db 列名匹配,也没有将值插入 db

if request:
    user=User()
    for k,v in request.POST.items():
        if str(k)!="csrfmiddlewaretoken":
            if(k=='name'):
                user.name=v     #like this data will be saved

             user.save()



if request:
    user=User()
    for k,v in request.POST.items():
        if str(k)!="csrfmiddlewaretoken":
                user.k=v     #like this data will not be saved

             user.save()

实际上我使用了相同的 db 列名和 html 表单标记名,因此 request.POST.keys() 与 db 列名匹配,但是如果我硬编码列它正在工作,但如果我从 request.post.keys 迭代并保存它不工作则直接

4

1 回答 1

0

This would not work because user.k implies you are trying to assign the value v to the attribute k of the User instance, which does not exist.

You can use setattr() for this purpose if you are bent on doing it this way.

for k,v in request.POST.items():
    if str(k)!="csrfmiddlewaretoken":
        setattr(user, k, v)
    user.save()
于 2013-08-28T17:22:33.703 回答