Django:如何检查用户名是否已经存在 [英] Django: how to check if username already exists

查看:595
本文介绍了Django:如何检查用户名是否已经存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不是Django的高级用户。我在网上看到了许多不同的方法,但是它们都是用于修改模型的,或者太复杂了,以至于我无法理解。
我在 MyRegistrationForm

i am not very advanced user of Django. I have seen many different methods online, but they all are for modified models or too complicated for me to understand. I am reusing the UserCreationForm in my 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

我很难理解或找到一种方法来检查用户输入的用户名是否已被使用。
因此,我只是使用它将我重定向到html,其中显示错误的用户名或密码不匹配:

I struggle to understand or find a way to check if the username that user enters is already taken or not. So i just use this to redirect me to html where it says bad username or passwords do not match:

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)

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

Here is my registration template(if needed):

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

但是我需要提出一些例外或类似的东西在用户重定向之前。也许当用户按下注册时,他/她会得到错误/警告,说用户名已被使用?

But i need to rasise some kind of exception or smth like that before user gets redirected. Maybe when user presses register he/she would get the error/warrning saying that username is already taken? Is that possible?

推荐答案

您可以使用 存在

You can use exists:

from django.contrib.auth.models import User

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

这篇关于Django:如何检查用户名是否已经存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆