[Django]-Django method to change User email not working

12👍

ChangeEmail is a normal form. These don’t have save methods – only ModelForms do. You’re correctly setting the user email from the form’s cleaned_data – but you should be saving the user1 object, not the form.

Also, it’s best not to redirect away on validation failure. Leave out that first else clause, and move the variables/render_to_response lines back one indentation level, and the form will be redisplayed with any errors.

2👍

views.py:

def change_email(request, username):
        # a common django idiom for forms
        form1 = ChangeEmail(request.POST or None)
        user1 = User.objects.get(username=username)
        if form1.is_valid():
            #check that emails are the same
            if form.cleaned_data['email1'] == form.cleaned_data['email2']:
                user1.email = form.cleaned_data['email1']
                #Save the user object here, since we're not dealing with a ModelForm
                user1.save()
                return HttpResponseRedirect('/register/success')
        # We're presenting them with the empty form if something went wrong
        # and redisplaying. The form's field errors should be printed out in
        # the template
        else:
            user = User.objects.get(username=username)
            email = user.email                
            variables = RequestContext(request, {
            'form': form,
            'email': email
        })
        return render_to_response('registration/email.html', variables)

Leave a comment