How to use django UserCreationForm correctly

空扰寡人 提交于 2020-01-02 03:13:29

问题


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.


回答1:


  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()
...


来源:https://stackoverflow.com/questions/13900357/how-to-use-django-usercreationform-correctly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!