Django方法更改用户电子邮件无法正常工作

时间:2011-12-23 17:39:18

标签: python django forms

我正在尝试创建一个页面,用户可以看到他们当前的电子邮件是什么,并根据需要进行更改。如果表单无效,我只是使用一个非常简单的表单和一个非常简单的HttpResponseRedirect进行测试。但是,如果表单无效,我的电子邮件既不会改变用户也不会失败。我不确定是什么导致了这个

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

提前感谢您的帮助。

修改

我已映射以呈现表单的网址为/user/testuser/email。我试图在字段中输入无效输入以获取错误消息,但是当我按下提交时,它会将我重定向回/user/testuser页面,该页面显示有关用户的信息。我的更改电子邮件模板如下:

{% 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 %}

2 个答案:

答案 0 :(得分:12)

ChangeEmail是一种正常形式。这些没有save方法 - 只有ModelForms这样做。您正确地从表单的cleaning_data设置用户电子邮件 - 但您应该保存user1对象,而不是表单。

此外,最好不要在验证失败时重定向。省略第一个else子句,并将变量/ render_to_response行移回一个缩进级别,表单将重新显示任何错误。

答案 1 :(得分: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)