I want to reset password in django app by visiting a certain url and passing e-mail by POST method. That's because I want to use it in an android app, which will have its own form. So, I thought I could create a custom password reset form and then save it, but it doesn work.
from django.contrib.auth.forms import PasswordResetForm
class Custom_password_reset_form(PasswordResetForm):
def __init__(self, email, **kwargs):
super(Custom_password_reset_form, self).__init__(**kwargs)
self.email = forms.EmailField(initial=email, max_length=254)
def mobile_password_reset(request):
"""Sends mail with password reset link."""
email = request.POST.get('email')
my_form = Custom_password_reset_form(email)
if my_form.is_valid():
print 'valid'
my_form.save()
else:
print 'not valid'
print my_form._errors
return render(...)
Validation always fails, giving empty my_form._errors list. What am I missing here? Or maybe there is some better way to do this?
Correct code:
The custom class is unnecessary, and should be removed. The password resetting method should look like this:
def mobile_password_reset(request):
"""Sends mail with password reset link."""
my_form = PasswordResetForm(request.POST)
if my_form.is_valid():
my_form.save()
return JsonResponse({'success': True})
else:
return JsonResponse({'success': False})
It's important to note, that without django.contrib.sites app added to settings, my_form.save() will not work. It could be also fixed by adding this argument: my_form.save(request=request).