1

我有一个允许用户创建用户帐户的表单。问题是,每当用户提交已通过系统获取的用户名时。该表单不会引发错误,但会在缺少字段时引发错误。有人可以帮助我吗

def Registration(request):  
    form = UserRegistration()
    if request.method =='POST':
        form = UserRegistration(request.POST)
        if form.is_valid():
            user = User.objects.create_user(
                username=form.cleaned_data['username'], 
                email=form.cleaned_data['email'], 
                password=form.cleaned_data['password']
                )
            user.is_active = True
            user.save()
             return render(request,'choose.html',{'form':form})

    return render(request, 'register.html', {'form': form},)

我的表格.py

class UserRegistration(forms.Form):
    username = forms.CharField()
    email = forms.EmailField(error_messages={'required':'Error Missing Field , Please Fill this Field'})

    password = forms.CharField(
    widget=forms.PasswordInput(render_value=False)
    )

    def clean(self):
            cleaned_data = super(UserRegistration, self).clean()
            username = cleaned_data.get("username")
            password = cleaned_data.get("password")

            user = User.objects.filter(username=username)
            if user :
                raise forms.ValidationError(
                        "That user is already taken , please select another ")


            return cleaned_data

我的模板

<form method ="POST">
    {% csrf_token %}


<span id="error">{{form.username.errors}}</span>
<span id="error2">{{form.email.errors}}</span>
<span id="error3">{{form.password.errors}}</span>

{{form.username}}
{{form.email}}
{{form.password}}
    <input type = "submit" value= "save" id="box2"/>
</form>
4

2 回答 2

3

您应该使用exists[0] 方法:

user = User.objects.filter(username=username)
if user.exists():
    raise forms.ValidationError("That user is already taken")

编辑:

尝试使用以下clean_username方法:

class UserRegistration(forms.Form):
    ....

    def clean_username(self):
        username = self.cleaned_data['username']
        if User.objects.filter(username=username).exists():
            raise forms.ValidationError("That user is already taken")
        return username

您可以添加一个测试以确保它有效:

from django.test import TestCase

class TestUniqueUsername(TestCase):

    def test_unique_username(self):
        User.objects.create(username='test', password='test', email='test@django.com')
        form = UserCreationForm(data={'username': 'test'})
        self.assertFalse(form.is_valid())

[0] https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.exists

于 2013-05-13T02:44:13.163 回答
0

试试这个代码

class UserRegistration(forms.Form):
    username = forms.CharField()
    email = forms.EmailField(error_messages={'required':'Error Missing Field , Please Fill this Field'})

    password = forms.CharField(
        widget=forms.PasswordInput(render_value=False)
    )

    def clean_username(self):
        cleaned_data = self.cleaned_data
        username = cleaned_data.get("username")
        user = User.objects.filter(username=username)
        if user.count() > 0:
            raise forms.ValidationError("That user is already taken , please select another ")
        return username

这会成功的。

于 2013-05-13T02:43:26.673 回答