I create a registration form on HTML ajax pull the data and send it to UserCreationForm via a function in views.py. But when I check the user I realized the password is not saved. I am using ajax so I took the data per field. And in the view function, I had to add the field values one by one. I used set_password but didn't help.
Any help will very appreciated thank you My Form:
class RegisterForm(UserCreationForm):
username = forms.CharField(max_length=100 , widget=forms.TextInput(
attrs={'class': "form-control"}))
email = forms.EmailField(max_length=100, widget=forms.EmailInput())
password1 = forms.CharField(widget=forms.PasswordInput(
attrs={'class': "form-control"}))
password2 = forms.CharField(widget=forms.PasswordInput(
attrs={'class': "form-control"}))
email.widget.attrs.update({'class': 'form-control'})
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
user.email = self.cleaned_data['email']
user.set_password(self.cleaned_data['password1'])
if commit:
user.save()
return user
My View:
def home(request):
register_form = RegisterForm()
workshop_form = WorkshopCreateForm
if request.method == 'POST':
register_form = RegisterForm(request.POST)
username = request.POST.get('username')
print(username)
email = request.POST.get('email')
password1 = request.POST.get('pass1')
password2 = request.POST.get('pass2')
if register_form.is_valid():
pended_form = register_form.instance
pended_form.username = username
pended_form.email = email
if password1 == password2:
pended_form.set_password(password1)
pended_form.save()
ctx = {
'username': pended_form.username,
'password': pended_form.password,
'created': True,
'success': True,
'status':'You created your account',
}
return JsonResponse(ctx)
else:
ctx = {
'username': '',
'password': '',
'created': False,
'success': False,
'status':'error',
'msg': _('Passwords do not match')
}
return JsonResponse(ctx)
#! TODO: Create a function and import login func from there
else:
ctx = {
'created': False,
'success': False,
'status':'error',
'msg': _('You need to enter a valid username and email')
}
return JsonResponse(ctx)
return render(request, 'web/home.html', {'register_form':register_form})
CodePudding user response:
just create a new user.
User.create.objects(username, email)
user.set_password(password)
user.save()
you can do this in your view
CodePudding user response:
I needed to use the RegisterForm() directly without parsing. I don't need to parse the data. I just put the data inside of RegisterForm() so the problem is solved.
if request.method == 'POST' and request.POST.get("operation") == "register":
register_form = RegisterForm(request.POST)
if register_form.is_valid():
register_form.save()
return JsonResponse(ctx)