简体   繁体   English

如何正确使用django UserCreationForm

[英]How to use django UserCreationForm correctly

I am new to Django and am just starting my first website. 我是Django的新手,刚刚开始我的第一个网站。 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. 我使用内置视图进行登录和注销但没有注册,在文档中,它说我应该使用内置形式: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). 它工作正常但我不满意,因为这个代码是在views.py中编写的,它处理我的应用程序的核心(多项选择题)。

My questions are : 我的问题是:

  • Is this the correct way of using the UserCreationForm 这是使用UserCreationForm的正确方法吗?
  • Where could I put this code so it would be separated from the rest of my app 我在哪里可以放置这些代码,以便它与我的应用程序的其余部分分开

Thank you for your answers. 谢谢您的回答。

  1. Django is modular, so you can write a separate accounts or user management app that can handle user creation, management. Django是模块化的,因此您可以编写一个单独的帐户用户管理应用程序,可以处理用户创建和管理。 In that case, you put the code for register in the views.py of accounts app. 在这种情况下,你把代码registerviews.py 帐户应用程序。

  2. You can directly save the UserCreationForm which will give you user object. 您可以直接保存UserCreationForm ,它将为您提供用户对象。

example: 例:

...
form = UserCreationForm(request.POST)
if form.is_valid():
   user = form.save()
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM