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

ppt*_*ptt 12 python django validation registration username

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

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
Run Code Online (Sandbox Code Playgroud)

我很难理解或找到一种方法来检查用户输入的用户名是否已被使用.所以我只是用它来重定向到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)
Run Code Online (Sandbox Code Playgroud)

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

{% 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 %}
Run Code Online (Sandbox Code Playgroud)

但是我需要在用户重定向之前稍微提出某种异常或类似的事件.也许当用户按下注册时,他/她会收到错误/警告说用户名已被占用?那可能吗?

Jun*_*sor 19

你可以使用exists:

from django.contrib.auth.models import User

if User.objects.filter(username=self.cleaned_data['username']).exists():
    # Username exists
    ...
Run Code Online (Sandbox Code Playgroud)


Anz*_*zel 6

您可以检查方法是否username存在clean_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."))
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您可以在注册表单中显示错误,而无需重定向到另一个页面。

更新:

正如@Spacedman指出的,关于在DB级别上检查Form逻辑上的用户名唯一性的竞赛条件的一个正确点,尽管您获得此机会的可能性很小,但如果您这样做的话,则可能值得一读:

如何在Django中通过唯一检查来避免竞争条件

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)
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。

  • 用户名是唯一的,因此只需尝试创建它并捕获导致的错误。这样,当另一个会话在测试存在与创建会话之间使用相同的用户名进行测试时,您将避免出现竞争状况。 (3认同)