How to create a user in Django?

后端 未结 4 887
不思量自难忘°
不思量自难忘° 2020-12-12 18:37

I\'m trying to create a new User in a Django project by the following code, but the highlighted line fires an exception.

def createUser(request):
    userNam         


        
4条回答
  •  佛祖请我去吃肉
    2020-12-12 19:16

    If you creat user normally, you will not be able to login as password creation method may b different You can use default signup form for that

    from django.contrib.auth.forms import UserCreationForm
    

    You can extend that also

    from django.contrib.auth.forms import UserCreationForm
    
    class UserForm(UserCreationForm):
        mobile = forms.CharField(max_length=15, min_length=10)
        email = forms.EmailField(required=True)
        class Meta:
            model = User
            fields = ['username', 'password', 'first_name', 'last_name', 'email', 'mobile' ]
    

    Then in view use this class

    class UserCreate(CreateView):
        form_class = UserForm
        template_name = 'registration/signup.html'
        success_url = reverse_lazy('list')
    
        def form_valid(self, form):
            user = form.save()
    

提交回复
热议问题