Hi everyone !
I’m a little bit confused here because I’m working on User registration and connection with Django.
I browsed the documentation here : https://docs.djangoproject.com/en/3.0/topics/auth/
But it seems that there is no real “best way” to manage it.
Some will use UserCreationForm and AuthenticationForm, some others will make their own models some others will use the User Model… I’m just lost to be honest…
Could someone give me a clue of what is the safest and best way to manage users (registration and login) ?
Here is my actual way of doing this :
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
# Create your views here.
def user_register(request):
if request.method == "POST":
form = UserCreationForm(data=request.POST)
if form.is_valid():
form.save()
return redirect("/")
else:
print(form.errors)
else:
form = UserCreationForm()
template_name = "register.html"
context = {
"form":form,
}
return render(request, template_name, context)
def user_login(request):
if request.method == "POST":
form = AuthenticationForm(data=request.POST)
if form.is_valid():
username = form.cleaned_data["username"]
password = form.cleaned_data["password"]
user = authenticate(request,username=username,password=password)
if user is not None:
login(request,user)
return redirect("/")
else:
print(user.errors)
else:
print(form.errors)
else:
form = AuthenticationForm()
template_name = "login.html"
context = {
"form":form,
}
return render(request, template_name, context)
Thank you in advance