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 %}
ChangeEmailis a normal form. These don’t havesavemethods – only ModelForms do. You’re correctly setting the user email from the form’s cleaned_data – but you should be saving theuser1object, not the form.Also, it’s best not to redirect away on validation failure. Leave out that first
elseclause, and move the variables/render_to_response lines back one indentation level, and the form will be redisplayed with any errors.