在django python中编辑配置文件

时间:2018-04-20 11:06:36

标签: python django

我正在添加一些功能,允许用户编辑他们的个人资料页面信息。当用户更新其信息并点击提交时,他们会收到NameError,说明user未定义。以下是我尝试实现编辑功能的方法。

形式

#this is all the information that the user is allowed to edit. 
class UpdateProfile(forms.ModelForm):
    username = forms.CharField(required=False)
    email = forms.EmailField(required=False)
    first_name = forms.CharField(required=False)
    last_name = forms.CharField(required=False)
    age = forms.IntegerField(required=False)
    height = forms.IntegerField(required=False)
    weight = forms.IntegerField(required=False)

    class Meta:
        model = User
        fields = ('username', 'email', 'first_name', 'last_name', 'age', 'height', 'weight')

    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(RegisterUserForm, self).save(commit=False)
        user.email = self.cleaned_data['email']
#This is where i am trying to save the new information. 
        if commit:
            user.save()
#This is where i am returning the user. 
        return user

视图

def update_profile(request):
    args = {}

    if request.method == 'POST':
        form = UpdateProfile(request.POST, instance=request.user)
        form.actual_user = request.user
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('account:profile.html'))
    else:
        form = UpdateProfile()

    args['form'] = form
    return render(request, 'account/edit_profile.html', args)

0 个答案:

没有答案