简体   繁体   English

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

[英]Django saving updated database values from form

I am trying to allow a user to edit their profile. 我正在尝试允许用户编辑其个人资料。 In the post method I want to save the new data over the old data in the same row. 在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'})

This code I believe is creating a new database row when the post method is called. 我相信这段代码会在调用post方法时创建一个新的数据库行。 How do I get it to update the existing row in a clean looking solution? 我如何在干净的解决方案中更新现有行?

如果您使用Django的UpdateView则它将保存ModelForm ..来处理许多这些详细信息。包括保存更新,成功重定向用户以及在出现问题时显示错误时重新显示表单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM