Can you trigger a forms style error from a view?

7 views
Skip to first unread message

John Shaver

unread,
Sep 22, 2011, 8:53:45 PM9/22/11
to django...@googlegroups.com
I'm designing a user registration form for my app. I need to verify
that the username they're using is not already in use before trying to
create the user. If the username already exists, I want to be able to
generate a form style error that says "Sorry that username is already
in use."

The only way I could find to do is with 'raise ValidationError'()' in
the clean() function. However, trying to query my User model to see
if that username is already take does not work from the clean()
function. On the other hand, I cannot find a way to set the error in
the form object from inside the view.

I prefer to do this from inside of the view, rather than from the
clean function. I already have several validation rules there that I
created, but I'd prefer to keep the Form class separate from my
models. Any suggestions?

-John

Daniel Roseman

unread,
Sep 23, 2011, 2:47:50 PM9/23/11
to django...@googlegroups.com
On Thursday, 22 September 2011 21:53:45 UTC+1, John Shaver wrote:

The only way I could find to do is with 'raise ValidationError'()' in
the clean() function.  However, trying to query my User model to see
if that username is already take does not work from the clean()
function.

Why not? That is exactly where you should do it. In fact, look at the code for Django's own signup form - django.contrib.auth.forms, the clean_username method, which does exactly that.
--
DR.

Kurtis

unread,
Sep 23, 2011, 3:23:17 PM9/23/11
to Django users
Check out http://groups.google.com/group/django-users/browse_thread/thread/40118d7879bbb228#
... I just asked a very similar question recently.
Reply all
Reply to author
Forward
0 new messages