简体   繁体   English

Django 1.7-使用表单更新用户记录

[英]Django 1.7 - update a user record using a form

I have created a form to update the existing user profile. 我创建了一个表格来更新现有的用户配置文件。 But when i save the form it shows the error user already exists. 但是,当我保存表格时,它表明错误用户已经存在。

I used another approach by getting the user profile and then updating each field, but in that case each field has to be validated? 我使用另一种方法来获取用户个人资料,然后更新每个字段,但是在那种情况下,每个字段都必须经过验证?

Any clue how to save the form as an update not as a new entry? 有什么线索如何将表单保存为更新而不是新条目?

I suggest using UpdateView , one of Django's class-based-views for generic editing: 我建议使用UpdateView ,这是Django基于类的视图之一,用于常规编辑:

class django.views.generic.edit.UpdateView django.views.generic.edit.UpdateView类

A view that displays a form for editing an existing object, redisplaying the form with validation errors (if there are any) and saving changes to the object. 该视图显示用于编辑现有对象的表单,重新显示带有验证错误的表单(如果有)并保存对对象的更改。 This uses a form automatically generated from the object's model class (unless a form class is manually specified). 这将使用从对象的模型类自动生成的表单(除非手动指定了表单类)。

I managed to get the answer, i imported the form to 我设法得到答案,我将表格导入

import the user that i want to edit 导入我要编辑的用户

u = User.objects.get(username = user_name) u = User.objects.get(用户名=用户名)

creating the form with values from existing in database and updating with values from POST 使用数据库中现有的值创建表单,并使用POST中的值进行更新

user_form = UserEditForm(request.POST,instance=u) user_form = UserEditForm(request.POST,instance = u)

save the form, since it already has existing record it will update 保存表单,因为它已经具有现有记录,它将更新

user_form.save() user_form.save()

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

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