Reputation: 2011
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.
Upvotes: 1
Views: 904
Reputation: 136
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')
Upvotes: 1