0

我试图在 django 中修改 UserRegistationFrom 以使每个电子邮件地址唯一

我是 django 的菜鸟。因此,通过遵循教程和 stuakoverflow 问题,我写了这个来检查电子邮件是否存在

顺便说一句,我在视图中写了所有内容以进行测试

from django.http import HttpResponse
from django.shortcuts import render
from django.contrib.auth.models import User
from django import forms
from django.contrib.auth.forms import UserCreationForm

class Signup(UserCreationForm):
    email = forms.EmailField(required=True)

    def clean_email(self):
        email = self.cleaned_data['email']
        try:
            user = User.objects.get(email=email)
        except User.DoesNotExist:
            return email
        raise forms.ValidationError("You have forgotten about Fred!")



def index(request):
    if request.method == "POST":
        signup = Signup(request.POST)

        if signup.is_valid():
            return HttpResponse("All is well")
        else:
            return render(request,'website/index.html',{'form':Signup})

    return render(request,'website/index.html',{'form':Signup()})

def private(request):
    return HttpResponse("Ok")

而且,我收到了这个错误

ValidationError at /
[u'Error']
Request Method: GET
Request URL:    http://127.0.0.1:8000/
Django Version: 1.5.4
Exception Type: ValidationError
Exception Value:    
[u'Error']

为什么我有这个错误?以及如何解决?

4

1 回答 1

0

好的,我已经修复了这个错误 :) 问题在于生成视图

所以正确的代码吧

from django.http import HttpResponse
from django.shortcuts import render
from django.contrib.auth.models import User
from django import forms
from django.contrib.auth.forms import UserCreationForm

class Signup(UserCreationForm):
    email = forms.EmailField(required=True)

    def clean_email(self):
        email = self.cleaned_data['email']

        try:
            u = User.objects.get(email=email)
        except User.DoesNotExist:
            return email

        raise forms.ValidationError("Error")




def index(request):
    if request.method == "POST":
        signup = Signup(request.POST)

        if signup.is_valid():
            return HttpResponse("All is well")
        else:
            return render(request,'website/index.html',{'form':signup})

    return render(request,'website/index.html',{'form':Signup()})

谢谢谁试图帮助我

于 2013-10-04T19:57:36.193 回答