Wednesday, October 17, 2012

Django Login and Sign-Up Page Together

It is very common to combine login and sign-up form in one page, so I implemented it in django. Here's how I do it.

First, create UserForm class which contains whatever information you need, such as: username, password, full name, address, email, gender, etc.

Second, add login url to your urls.py, something like the following:
(r'^/login/$', 'django.contrib.auth.views.login', { 'template_name': 'myapp/login.html', 'reg_form': UserForm() }),

Third, create in your template folder myapp/login.html which content is like shown in docs.djangoproject.com/en/dev/topics/auth/ (search for sample registration/login.html)
Make sure you use the exact same variable name (form, next, etc), unless you know what you are doing.
Also, in this template, add another html form and render your UserForm object (in my case the variable name is reg_form.

Fourth, create sign_up view, which perform whatever it is necessary in order to save the new user. Make sure you add { 'form': django.contrib.auth.forms.AuthenticationForm() } to the context data.

Sixth, add sign_up url to your urls.py, something like the following:
(r'^/sign-up/$', myapp.views.sign_up ),

Notes:
I created my own User class with additional information that django user (auth_user) does not provide. In order to do that, I create (custom) User with a OneToOne relationship with django user which is also the primary_key.

That's how I do it. Hopefully, give you some ideas if you want to implement something similar.