简体   繁体   中英

Django: How to create a new user with a custom registration form

I am trying to make a custom registration form in Django, using HTML and CSS and not Django's form.as_p and Bootstrap. I have the following code in views.py:

def signUp(request):
   if request.POST:
       username = request.POST['username']
       email = request.POST['email']
       password = request.POST['password']
       password_confirm = request.POST['password-confirm']
       if(valid_form(username, email, password, password_confirm)) {
          #create the new user
       } else {
          #send some error message
       }    
return render(request, 'index.html')

I have my own function valid_form to check if the form fields entered by the user are valid. However, I am not sure how I can create the new user using Django's User Model. In all of the code examples regarding registration forms I have seen something like this:

def register(request):
if request.method == 'POST':
    form = UserCreationForm(request.POST)
    if form.is_valid():
        form.save()
        return redirect('main-page')
else:
    form = UserCreationForm()
return render(request, 'users/register.html', {'form': form})

Where they use form.save() to create the new user. Since I am not using Django's form model, how can I create a new user after validating form data? Any insights are appreciated.

You can create new Users in your web app by modifying your views.py as below:

from django.contrib.auth import get_user_model


def signUp(request):
   if request.POST:
       username = request.POST['username']
       email = request.POST['email']
       password = request.POST['password']
       password_confirm = request.POST['password-confirm']
       if(valid_form(username, email, password, password_confirm)) {
          user = get_user_model().objects.create(
              username=username,
              email=email,
          )
          user.set_password(password)
          user.save()
       } else {
          #send some error message
       }    
return render(request, 'index.html')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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