I created a signup page using Django's builtin signup forms.Here is my code below
forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class SignUpForm(UserCreationForm):
email = forms.EmailField(max_length=254, help_text='Please provide a valid email address.')
class Meta:
model = User
fields = ('username', 'email', 'password1', 'password2')
def clean(self):
cleaned_data = super(SignUpForm, self).clean()
username = cleaned_data.get("username")
email = cleaned_data.get("email")
check_email = User.objects.filter(email=email)
if check_email:
raise forms.ValidationError(
"You are already registered!")
return cleaned_data
check_username = User.objects.filter(username=username)
if check_username:
raise forms.ValidationError(
"A user with that username already exists")
return cleaned_data
In my views.py this is how I do the authentication for signup
views.py
@csrf_exempt
def signup_users(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('password1')
user = authenticate(username=username, password=raw_password)
print("signup authencticate", user)
login(request, user)
return redirect('/')
else:
form = SignUpForm()
return render(request, 'signup.html', {'form': form})
Here is my code to handle user login
@csrf_exempt
def login_view(request):
print(request.user.is_authenticated())
if request.POST:
email = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(email=email, password=password)
if user is not None:
if user.is_active:
login(request, user)
return HttpResponseRedirect('/')
else:
return render(request, "login.html")
else:
return render(request, "login.html")
When I signup, everything seems fine but when I try to login, it just won't let me login.
So when I checked the django admin
, this is what I found
Username: tech1
Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.
Password:
Invalid password format or unknown hashing algorithm.
Raw passwords are not stored, so there is no way to see this user's password, but you can change the password using this form.
I don't quite understand why the user password is not stored at the time of signup?
I searched for it and I found out from this answer using User.objects.get_or_create() gives invalid password format in django? that django encrypts the password before storing and I should use something like
user, created = User.objects.get_or_create(username="testuser2")
user.set_password('123')
But I am not quite sure where to put this in my code or how does this help?What is going on?