Django: how to check if username already exists

pptt picture pptt · Apr 12, 2015 · Viewed 22.9k times · Source

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

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?

Answer

JuniorCompressor picture JuniorCompressor · Apr 12, 2015

You can use exists:

from django.contrib.auth.models import User

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