如何使用user.id将值保存到数据库-Django

时间:2019-05-19 19:37:16

标签: python django

我想保存用户输入到存储库中的值。但是,如果用户已经输入了一个值,我希望它进行更新。

现在正在保存数据。但它无法更新。

我正在使用Django

forms.py

    class Meta():
        model = UserProfileInfo
        fields = ('apikey', 'apivalue', 'apisupplier')

views.py

def user_set_api(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(username=username, password=password)
        current_user = request.user
        user_form = UserProfileInfoForm(data=request.POST)
        user_id = current_user.id
        print('UserId:', user_id)
        if user_form.is_valid() and user_id:
            user_form.save(request.user)
            print('User: ', user, 'Userformid:', UserProfileInfo(['user_id']))
        else:
            print(user_form)
    else:
        keysvalue = UserProfileInfoForm()
    return render(request, 'form.html',
                  {'apisupplier': UserProfileInfo})

models.py

    user = models.OneToOneField(User, default=None, null=True, on_delete=models.CASCADE)
    apisupplier = models.CharField(max_length=40, blank=True, default="null")
    apikey = models.CharField(max_length=40, blank=True, default="null")
    apivalue = models.CharField(max_length=40, blank=True, default="null")

    def __str__(self):
        template = '{0.user} {0.apikey} {0.apivalue} {0.apisupplier}'
        return template.format(self)```

1 个答案:

答案 0 :(得分:0)

我不确定为什么要将用户ID传递给form.save()。您需要将用户对象传递给表单实例化:

if request.method == 'POST':
    ...
    user_form = UserProfileInfoForm(data=request.POST, instance=request.user)
    if user_form.is_valid()
        user_form.save()
        ...
else:
    user_form = UserProfileInfoForm(instance=request.user)
return render(request, 'form.html',
              {'apisupplier': UserProfileInfo, "user_form": user_form})