I have a SignUpForm written in forms.py in my Twitter clone project that renders a simple sign up form to the user. It’s supposed to take the data user entered and save it in the database. But I’m having issue. The data is not getting saved in database & Sign up page redirects to itself immediately after I enter Submit button. I checked my views.py file & came to know that form.is_valid()
is returning false
hence data not going further.
This was working as expected before I changed my input styles to Google Material Design 3 from Bootstrap.
Here I provided views.py & forms.py for reference:
forms.py:
class SignUpForm(UserCreationForm):
first_name = forms.CharField(
label='First Name',
max_length = 20,
widget = forms.TextInput(
attrs = {
'class': 'md-text-field__input',
}
)
)
last_name = forms.CharField(
label='Last Name',
max_length = 30,
widget = forms.TextInput(
attrs = {
'class': 'md-text-field__input',
}
)
)
email = forms.EmailField(
label='Enter Email',
widget = forms.EmailInput(
attrs = {
'class': 'md-text-field__input',
}
)
)
class Meta:
model = User
fields = ['first_name', 'last_name', 'username', 'email', 'password1', 'password2']
def __init__(self, *args, **kwargs):
super(SignUpForm, self).__init__(*args, **kwargs)
self.fields['username'].widget = forms.TextInput(
# label = 'Enter username',
attrs = {
'class': 'form-control',
'placeholder': 'Your Username'
}
)
self.fields['username'].help_text = '<span class="form-text text-muted"><small>Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.</small></span>'
self.fields['password1'].widget = forms.PasswordInput(
# label='Enter your password',
attrs={
'class': 'form-control',
'placeholder': 'Your Password',
'type': 'password'
}
)
self.fields['password2'].widget = forms.PasswordInput(
# label='Confirm your password',
attrs={
'class': 'form-control',
'placeholder': 'Confirm Password',
'type': 'password'
}
)
And here is views.py for signup_user()
:
def signup_user(request):
form = SignUpForm()
if request.method == 'POST':
form = SignUpForm(request.POST)
# problem is here
if form.is_valid():
print(form.errors)
form.save()
username = form.cleaned_data['username']
password = form.cleaned_data['password1']
# Log In user
user = authenticate(username = username, password = password)
login(request, user)
messages.success(request, ('You\'ve been registered Successfully. Welcome to Twitter!'))
return redirect('home')
else:
messages.error(request, ('Something went wrong. Please Try again.'))
print('something\'s wrong with this form. this form is not valid.')
return render(request, 'signup.html', {'form': form})
else:
form = SignUpForm()
return render(request, 'signup.html', {'form':form})
And one more thing, input entered for the Password is not showing bullet points despite giving input style as password.
I hope my question is clear and concise. Let me know if need more clarity.
Thank you.