简体   繁体   中英

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 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. How do I get it to update the existing row in a clean looking solution?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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