Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use django UserCreationForm correctly

I am new to Django and am just starting my first website. I am trying to set registration for new users.

I used the built in view for login and logout but there is none for registration, in the doc, it says that I should use built in form : UserCreationForm.

The code of my view is :

def register(request):
if request.method =='POST':
    form = UserCreationForm(request.POST)
    if form.is_valid():
        user = User.objects.create_user(form.cleaned_data['username'], None, form.cleaned_data['password1'])
        user.save()
        return render_to_response('QCM/index.html') # Redirect after POST
else:
    form = UserCreationForm() # An unbound form

return render_to_response('register.html', {
    'form': form,
},context_instance=RequestContext(request))

It works fine but I am not satisfied as this code is written in the views.py that handles the core of my application (multiple choice question).

My questions are :

  • Is this the correct way of using the UserCreationForm
  • Where could I put this code so it would be separated from the rest of my app

Thank you for your answers.

like image 341
ltbesh Avatar asked Dec 16 '12 10:12

ltbesh


1 Answers

  1. Django is modular, so you can write a separate accounts or user management app that can handle user creation, management. In that case, you put the code for register in the views.py of accounts app.

  2. You can directly save the UserCreationForm which will give you user object.

example:

...
form = UserCreationForm(request.POST)
if form.is_valid():
   user = form.save()
...
like image 93
Rohan Avatar answered Sep 16 '22 16:09

Rohan