user670595
user670595

Reputation:

Django method to change User email not working

I am attempting to create a page where a user can see what their current email is and change it if they would like. I am just testing with a very simple form and a very simple HttpResponseRedirect if the form is not valid. However neither my email is changing for the user nor is my failure response if the form is not valid working. I am not sure what is causing this

forms.py:

    class ChangeEmail(forms.Form):
        email1 = forms.EmailField(label=u'Type new Email')
        email2 = forms.EmailField(label=u'Type Email again') 

views.py:

def change_email(request, username):
    if request.method == 'POST':
        user1 = User.objects.get(username=username)
        form1 = ChangeEmail(request.POST)
        if form1.is_valid():
            user1.email = form.cleaned_data['email1']
            form1.save()
            return HttpResponseRedirect('/register/success')
        else:
            return HttpResponseRedirect('/stupid')
    else:
        user = User.objects.get(username=username)
        email = user.email
        form = ChangeEmail()
        variables = RequestContext(request, {
            'form': form,
            'email': email
        })
        return render_to_response('registration/email.html', variables

Thanks for your help in advance.

EDIT:

The URL that I have mapped to render the form is /user/testuser/email. I am attempting to put in invalid input in to the fields to get an error message but when I push submit it redirects me back to /user/testuser page which displays info about the user. My change email template is below:

{% extends "base.html" %}
{% block title %}Change Email{% endblock %}
{% block head %}Change Email{% endblock %}
{% block content %}
<p> Current Email: {{ email }} </p>
<form method="post" action=".">{% csrf_token %}
  {{ form.as_p }}
  <input type="submit" value="Change Email" />
</form>
{% endblock %}

Upvotes: 3

Views: 2733

Answers (2)

jeffknupp
jeffknupp

Reputation: 6304

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)

Upvotes: 2

Daniel Roseman
Daniel Roseman

Reputation: 599876

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.

Upvotes: 12

Related Questions