Trong Truong
Trong Truong

Reputation: 301

Django: what kind of exceptions does create_user throw?

I want to catch them and return helpful messages to the user. The documentation https://docs.djangoproject.com/en/1.4/topics/auth/ says ValueError is raised when given an invalid username. There's also IntegrityError, when the username already exists. Are these all?

Is this the usual way to do it?

Upvotes: 3

Views: 2773

Answers (2)

aemdy
aemdy

Reputation: 3802

You can always take a look at source code easily since their moved to Github or find it in Python site-packages directory on your machine.

Just go to django/contrib/auth/ and analyze some code.

Upvotes: 0

Aamir Rind
Aamir Rind

Reputation: 39689

If you are not using Django Auth Forms then you have to do the validation manually. The simple way is when user submit the custom form you should check:

  • if username is valid, match with the regex e.g. \w+
  • check if username is already taken or not e.g. User.objects.filter(username=username).exists()
  • check if email is already used for an account e.g. User.objects.filter(email=email).exists()
  • then create the user

FYI: there are some already Django Auth packages e.g. django-allauth, django-userena and many more which handles all the stuff pretty well, instead of reinventing the wheel by your self.

Upvotes: 7

Related Questions