Django:如何检查用户名是否已经存在

2024-05-21 19:26:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我不是Django的高级用户。我在网上看到过很多不同的方法,但都是针对修改过的模型,或者太复杂,我无法理解。 我正在重用我的MyRegistrationForm中的UserCreationForm

class MyRegistrationForm(UserCreationForm):

    email = forms.EmailField(required=True)

    class Meta:
        model = User
        fields = ('username', 'email', 'password1', 'password2')

    def save(self, commit=True):
        user = super(MyRegistrationForm, self).save(commit=False)
        user.email = self.cleaned_data['email']
        user.set_password(self.cleaned_data["password1"])

        if commit:
            user.save()

        return user

我很难理解或者想办法检查用户输入的用户名是否已经被使用。 所以我就用这个把我重定向到html,上面写着错误的用户名或密码不匹配:

def register_user(request):
    if request.method == 'POST':
        form = MyRegistrationForm(request.POST)
        if form.is_valid():
            form.save()

            return HttpResponseRedirect('/accounts/register_success')
        else:
            return render_to_response('invalid_reg.html')


    args = {}
    args.update(csrf(request))

    args['form'] = MyRegistrationForm()
    print args
    return render_to_response('register.html', args)

这是我的注册模板(如果需要):

{% extends "base.html" %}

{% block content %}

<section>
<h2 style="text-align: center">Register</h2>
<form action="/accounts/register/" method="post">{% csrf_token %}

<ul>
{{form.as_ul}}
</ul>
<input type="submit" value="Register" onclick="validateForm()"/>

</form>

</section>
{% endblock %}

但在用户被重定向之前,我需要发出某种异常或类似的smth。也许当用户按下register时,他/她会得到一个错误/警告,说用户名已经被占用了?有可能吗?


Tags: 用户selfformregisterreturnifemailrequest
2条回答

您可以使用clean_username方法检查username是否存在,并引发ValidationError

def clean_username(self, username):
    user_model = get_user_model() # your way of getting the User
    try:
        user_model.objects.get(username__iexact=username)
    except user_model.DoesNotExist:
        return username
    raise forms.ValidationError(_("This username has already existed."))

如果是这种情况,您可以在注册表单中显示错误,而无需重定向到其他页面。

更新:

正如@Spacedman指出的,在检查表单逻辑上的用户名唯一性和DB级别的唯一性时,关于竞争条件的一个有效点是,尽管您不太可能获得这一点,如果您这样做的话,这里有相关的SO答案,可能值得一读:

How to avoid race condition with unique checks in Django

Race conditions in django

另一个更新

根据OP的评论,以下是对视图的另一个更改:

def register_user(request):
    # be DRY, the form can be reused for both POST and GET
    form = MyRegistrationForm(request.POST or None)

    # check both request is a POST and the form is valid
    # as you don't need to redirect for form errors, remove else block
    # otherwise it's going to redirect even form validation fails
    if request.method == 'POST' and form.is_valid():
        form.save()
        return HttpResponseRedirect('/accounts/register_success')
    # I use render so need not update the RequestContext, Django does it for you
    html = render(request, 'register.html', {'form': form})
    return HttpResponse(html)

希望这有帮助。

您可以使用^{}

from django.contrib.auth.models import User

if User.objects.filter(username=self.cleaned_data['username']).exists():
    # Username exists
    ...

相关问题 更多 >