Django从表单中保存更新的数据库值

时间:2017-05-12 01:56:46

标签: python django

我正在尝试允许用户编辑他们的个人资料。在post方法中,我想将新数据保存在同一行的旧数据中。

# Post method of class view in views.py
def post(self, request, username):
    try:
        user = User.objects.get(username=username)
    except User.DoesNotExist:
        raise Http404('The User "' + username + '" could not be found.')

    if (not request.user.is_authenticated):
        return HttpResponseForbidden()
    elif (user.id is not request.user.id):
        return HttpResponseForbidden()

    form = self.form_class(request.POST)

    if (form.is_valid()):

        # creates a new user object, does not save to the database yet
        profile = form.save(commit=False)

        # clean (normalized) data
        # ...
        profile.save()

        if (user.is_active):
            return redirect('/profile/' + user.username)

    return render(request, self.template_name, {'form': form, 'error_message': 'Oops, something went wrong'})

我相信这段代码在调用post方法时会创建一个新的数据库行。如何让它在一个干净的解决方案中更新现有的行?

0 个答案:

没有答案