Django编辑用户个人资料
我正在尝试在前面创建编辑个人资料"表单.发生的事情是我的表单(我不是100%确信)试图创建一个用户,而不是查找当前用户并更新其个人资料.所以我认为这就是问题所在.在这里检查了许多问题,但没有一个很清楚.我要编辑的字段是电子邮件,名字和姓氏.(另外,我想添加uda
I'm trying to create an "Edit Profile" form in the fronted. What happens is that my form(i'm not 100% sure) tries to create a user instead of finding the current user and update his profile. So I think that's the issue. Checked many questions here but none was clear enough. The fields I'm trying to edit are email, first name and last name. (Also I would like to add uda
forms.py
class UpdateProfile(forms.ModelForm):
username = forms.CharField(required=True)
email = forms.EmailField(required=True)
first_name = forms.CharField(required=False)
last_name = forms.CharField(required=False)
class Meta:
model = User
fields = ('username', 'email', 'first_name', 'last_name')
def clean_email(self):
username = self.cleaned_data.get('username')
email = self.cleaned_data.get('email')
if email and User.objects.filter(email=email).exclude(username=username).count():
raise forms.ValidationError('This email address is already in use. Please supply a different email address.')
return email
def save(self, commit=True):
user = super(RegistrationForm, self).save(commit=False)
user.email = self.cleaned_data['email']
if commit:
user.save()
return user
views.py
def update_profile(request):
args = {}
if request.method == 'POST':
form = UpdateProfile(request.POST)
form.actual_user = request.user
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('update_profile_success'))
else:
form = UpdateProfile()
args['form'] = form
return render(request, 'registration/update_profile.html', args)
您非常亲密.实例化表单时,需要将要修改的 User
对象作为 instance
参数传递.
You are very close. When you are instantiating the form, you need to pass the User
object you are modifying as the instance
argument.
从文档中
ModelForm的子类可以接受现有的模型实例作为关键字参数
instance
;如果提供了此参数,则save()将更新该实例.
A subclass of ModelForm can accept an existing model instance as the keyword argument
instance
; if this is supplied, save() will update that instance.
在您的代码中,它看起来像:
In your code, it would look like:
form = UpdateProfile(request.POST, instance=request.user)
if form.is_valid():
...
您可以在此处签出更多信息: https://docs.djangoproject.com/en/1.6/topics/forms/modelforms/#the-save-method
You can checkout more info here: https://docs.djangoproject.com/en/1.6/topics/forms/modelforms/#the-save-method