Issue
I have a sign up form that does not store the username properly, other fields are stored successfully. Shouldn't it save the username because it is in the fields ? I saw that I cannot login and this is because the row in the table does not have the username.
views.py
class SignUpFormView(FormView):
form_class = SignUpForm
template_name = 'users/authentication/login/signup.html'
def post(self, request):
form = self.form_class(data=request.POST)
if form.is_valid():
user = form.save(commit=False)
# some logic here
user.save()
messages.success(
request, "Great! You are able to login now.")
return redirect('login')
else:
messages.error(request, form.errors)
return redirect('login')
forms.py
class CustomUserCreationForm(UserCreationForm):
def clean_username(self):
username = self.cleaned_data["username"]
try:
TbUser.objects.get(username=username)
except TbUser.DoesNotExist:
return username
raise forms.ValidationError(self.error_messages['duplicate_username'])
class Meta(UserCreationForm.Meta):
model = TbUser
class SignUpForm(CustomUserCreationForm):
email = forms.EmailField()
customer_id = forms.CharField(label="Customer ID")
def clean_username(self):
data = self.cleaned_data['username']
if TbUser.objects.filter(username=data).exists():
raise forms.ValidationError(
"Username already exists. Pick another one")
def clean(self):
cd = self.cleaned_data
password1 = cd.get("password1")
password2 = cd.get("password2")
if password1 != password2:
raise ValidationError("Passwords did not match")
return cd
class Meta:
model = TbUser
fields = ['username', 'email', 'real_name', 'customer_id',
'password1', 'password2']
Solution
The clean_username
method of SignUpForm
does not return anything. You need to return cleaned data for it. So add return data
to the bottom of this method.
Answered By - black
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.