def user(request): if not request.user.is_authenticated(): messages.error(request, "Authentication required to access account information.") return redirect("/") u = User.objects.get(username=request.user) if request.method == "POST": pform = SetPasswordForm(user=u, data=request.POST) if pform.is_valid(): pform.save() messages.success(request, "Password Updated.") #else: # messages.warning(request, "Invalid Password.") mform = UserEmailForm(request.POST) if mform.is_valid(): m = mform.cleaned_data["email"] if m != u.email: u.email = m u.save() messages.success(request, "Email Address Updated.") else: messages.warning(request, "Invalid Email Address.") return redirect(".") #rc = RequestContext(request, { c = { 'form': QueryForm(), 'authform': AuthenticationForm(), 'passform': SetPasswordForm(request.user), 'emailform': UserEmailForm(instance=u), 'redirect': request.path, } #return render_to_response("account.html", rc) return render(request, "account.html", c)
def password_change(request, template_name='usuario/perfil/cambiar_clave.html', current_app=None, extra_context=None, expresion=None, tipo_mensaje=None, mensaje=None, palabra_clave=None): context = {} context.update(csrf(request)) # Determinar cuál formulario usar. # 'Asignar' no necesita contraseña anterior # 'Cambiar' necesita contraseña anterior accion = '' if palabra_clave == 'asignar': form = SetPasswordForm(user=request.user, data=request.POST or None) accion = 'cambiada' elif palabra_clave == 'cambiar': accion = 'actualizada' form = PasswordChangeForm(user=request.user, data=request.POST or None) if form.is_valid(): form.save() mensaje = u'Contraseña %s exitosamente' %(accion) tipo_mensaje = 'success' else: tipo_mensaje = 'error' for error in form.errors: mensaje = form.errors['%s' %(error)].as_text().replace('* ','') (tipo_mensaje, expresion) = msj_expresion(tipo_mensaje) context.update({'formulario':form}) context.update({'request':request}) context.update({'mensaje':mensaje}) context.update({'tipo_mensaje':tipo_mensaje}) context.update({'expresion':expresion}) return render_to_response(template_name, context)
def password_reset_confirm(request, key): template_name = 'doctor/password_reset_confirm.html' contexto = {} reset = get_object_or_404(PasswordReset, key = key) form = SetPasswordForm(user = reset.user, data = request.POST or None) if form.is_valid(): MIN_LENGTH = 8 password1 = form.cleaned_data['new_password1'] # At least one letter and one non-letter first_isalpha = password1[0].isalpha() if all(c.isalpha() == first_isalpha for c in password1): messages.success(request,'A senha deve conter pelo menos uma letra e pelo menos um dígito ou "\ "um caractere de pontuação.') form = SetPasswordForm(user = reset.user, data = request.POST) # At least MIN_LENGTH long elif len(password1) < MIN_LENGTH: messages.success(request,'A senha deve ter %d caracteres no mínimo.' % MIN_LENGTH) form = SetPasswordForm(user = reset.user, data = request.POST) else: form.save() contexto['success'] = True messages.success(request,'Sua senha foi criada com sucesso') contexto['form'] = form return render(request,template_name,contexto)
def password_reset_confirm(request, uidb64=None, token=None): if request.user.is_authenticated(): return HttpResponseRedirect(reverse("index")) context = {} UserModel = get_user_model() assert uidb64 is not None and token is not None try: uid = force_text(urlsafe_base64_decode(uidb64)) user = UserModel._default_manager.get(pk=uid) except (TypeError, ValueError, OverflowError, UserModel.DoesNotExist): user = None if user is not None and default_token_generator.check_token(user, token): valid_link = True title = _("Enter new password") if request.method == "POST": form = SetPasswordForm(user, request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse("players:password_reset_complete")) else: form = SetPasswordForm(user) else: valid_link = False title = _("Password reset failed") form = None context.update({"form": form, "title": title, "valid_link": valid_link}) context.update({"request": request}) return render(request, "players/password_reset/confirm.html", context)
def password_reset_confirm(request, uidb36=None, token=None): """View that checks the hash in a password reset link and presents a form for entering a new password. Based on django.contrib.auth.views. """ try: uid_int = base36_to_int(uidb36) except ValueError: raise Http404 user = get_object_or_404(User, id=uid_int) context = {} if default_token_generator.check_token(user, token): context['validlink'] = True if request.method == 'POST': form = SetPasswordForm(user, request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('users.pw_reset_complete')) else: form = SetPasswordForm(None) else: context['validlink'] = False form = None context['form'] = form return render(request, 'users/pw_reset_confirm.html', context)
def password_reset_confirm(request, key): try: reset = PasswordReset.objects.get(key=key) user = reset.user except PasswordReset.DoesNotExist: user = None if user is not None: validlink = True if request.method == 'POST': form = SetPasswordForm(user, request.POST) if form.is_valid(): form.save() reset.delete() return redirect('accounts.password_reset_done') else: form = SetPasswordForm(None) else: validlink = False form = None return render(request, 'accounts/password_reset_confirm.j.html', { 'validlink': validlink, 'form': form })
def password_reset_confirm(request, uidb36=None, token=None): token_generator = default_token_generator try: uid_int = base36_to_int(uidb36) user = User.objects.get(id=uid_int) except (ValueError, User.DoesNotExist): user = None if user is not None and token_generator.check_token(user, token): validlink = True if request.method == 'POST': form = SetPasswordForm(user, request.POST) if form.is_valid(): form.save() messages.success(request, _(u'Пароль изменён')) return redirect('/') else: form = SetPasswordForm(None) else: validlink = False form = None context = { 'form': form, 'validlink': validlink, } return render(request, 'account/password_reset_confirm.html', context)
def post(self, request,username): # Create a serializer with request.DATA serializer = self.serializer_class(data=request.DATA) old_password = request.DATA.get('old_password','') new_password1 = request.DATA.get('new_password1', '') new_password2 = request.DATA.get('new_password2', '') user = authenticate(username=username, password=old_password) result = {} result['errCode'] = 10000 result['errDesc'] = errMsg[10000] if user is None: result['errCode'] = 10003 result['errDesc'] = errMsg[10003] return Response(result, status=status.HTTP_200_OK) if not old_password or not new_password1 or not new_password2: result['errCode'] = 10018 result['errDesc'] = errMsg[10018] return Response(result, status=status.HTTP_200_OK) if serializer.is_valid(): # Construct the SetPasswordForm instance form = SetPasswordForm(user=user, data=serializer.data) if form.is_valid(): form.save() # Return the success message with OK HTTP status return Response(result, status=status.HTTP_200_OK) result['errCode'] = 10004 result['errDesc'] = errMsg[10004] logger.debug(serializer.errors) return Response(result, status=status.HTTP_200_OK)
def profileupdate(request): ## profile update form if request.method == 'POST' and 'profileupdate' in request.POST: profileform = ProfileUpdateForm(request.POST, request.FILES, instance=request.user) if profileform.is_valid(): profileform.save() messages.success(request, 'Profile details updated') return HttpResponseRedirect(reverse('profile-update')) else: profileform = ProfileUpdateForm(instance=request.user) ## password change form if request.method == 'POST' and 'passwordchange' in request.POST: passwordform = SetPasswordForm(request.user, request.POST) if passwordform.is_valid(): passwordform.save() messages.success(request, 'Password changed') return HttpResponseRedirect(reverse('profile-update') + '#body') else: passwordform = SetPasswordForm(request.user) return render(request, 'accounts/update.html', { 'profileform': profileform, 'passwordform': passwordform, })
def update(request, id): user = User.objects.get(id=id) if request.POST: user_form = UserForm(request.POST, instance=user) setpassword_form = SetPasswordForm(user, request.POST) new_password1 = request.POST.get('new_password1', '') new_password2 = request.POST.get('new_password2', '') if not new_password1 and not new_password2: if user_form.is_valid(): user_form.save() return HttpResponseRedirect(reverse('account_index')) else: if user_form.is_valid() and setpassword_form.is_valid(): user_form.save() setpassword_form.save() return HttpResponseRedirect(reverse('account_index')) else: user_form = UserForm(instance=user) setpassword_form = SetPasswordForm(user) return { 'user_form':user_form, 'setpassword_form':setpassword_form, 'id':id }
def confirm_reset_password(request, username, confirmation_code): logout(request) tagging = RecipientUserTagging.get_or_none(user__username=username) error = None if not tagging: error = "Unknown username" #elif tagging.is_confirmed: # error = "Registration is already complete." elif not tagging.confirm(confirmation_code): error = "Error confirming confirmation_code %s" % confirmation_code else: if request.POST: form = SetPasswordForm(tagging.user, request.POST) if form.is_valid(): form.save() success = tagging.confirm(confirmation_code) if not success: return render_response(request, 'procrasdonate/recipient_organizer_pages/account/confirmation_error.html', locals()) user = authenticate(username=username, password=form.cleaned_data['new_password1']) if user.is_active: login(request, user) user.message_set.create(message='Password reset complete!') return HttpResponseRedirect(reverse('recipient_organizer_dashboard')) else: return HttpResponseRedirect(reverse('login')) form = SetPasswordForm(tagging.user) instructions = """Enter a new password. It can be whatever you want, but it will be more secure if you use numbers and uppercase letters in addition to lowercase letters.""" return render_response(request, 'procrasdonate/recipient_organizer_pages/account/confirm.html', locals())
def change_pass(request): code = request.GET.get('code', '') if code: try: uid = fb_utils.get_userid(code, change_pass) if uid != request.user.fbprofile.fb_userid: messages.error(request, "Your facebook account did not" +\ " match the one registered with LitHub.") return redirect('bookswap.views.my_account') form = SetPasswordForm(user=request.user) if request.method=="POST": form = SetPasswordForm(request.user, request.POST) if form.is_valid(): form.save() messages.success(request, "Your password was "+\ "successfully changed.") return redirect("bookswap.views.my_account") return render(request, "fbconnect/password_change.html", {'form':form},) except ObjectDoesNotExist: return redirect('bookswap.views.my_account') except ValueError: return render(request, "fbconnect/code_error.html") else: messages.error(request, "There was an error getting your " +\ "information from facebook.") return redirect('django.contrib.auth.views.login')
def reset_password(request): if request.user.is_authenticated(): return HttpResponse(status=400) uidb36 = request.POST['uidb36'] token = request.POST['token'] try: uid_int = base36_to_int(uidb36) user = User.objects.get(id=uid_int) except (ValueError, ObjectDoesNotExist): user = None if user is not None and default_token_generator.check_token(user, token): form = SetPasswordForm(user, request.POST) if form.is_valid(): form.save() user = auth.authenticate( username=user.username, password=request.POST['new_password1']) auth.login(request, user) return HttpResponse(JSON_SUCCESS) else: return get_json_errors(form.errors) else: return HttpResponse(status=400)
def set_password(request): # This shows the signup form and displays errors if request.method == 'POST': # This form has been filled in by the user form = SetPasswordForm(request.user, request.POST) if form.is_valid(): form.save() logger.debug('Set password for ' + request.user.email) # Set a message and redirect # Django logs the user out after successful password set :( WTF # Crazy hack: http://stackoverflow.com/questions/15192808/django-automatic-login-after-user-registration-1-4 request.user.backend = "django.contrib.auth.backends.ModelBackend" auth_login(request, request.user) message = "Your password has been set!" messages.add_message(request, messages.SUCCESS, message) logger.debug(message) return redirect('accounts:profile') else: # initial, empty form form = SetPasswordForm(user=request.user) context = { 'form': form, } return render(request, 'registration/password_set_form.html', context)
def change_password(request): can_change_password = request.user.has_usable_password() if can_change_password: if request.POST: form = SetPasswordForm(request.user, request.POST) if form.is_valid(): form.save() if django.VERSION >= (1, 7): from django.contrib.auth import update_session_auth_hash update_session_auth_hash(request, form.user) messages.success(request, _("Your password has been changed successfully!")) return redirect('wagtailadmin_account') else: form = SetPasswordForm(request.user) else: form = None return render(request, 'wagtailadmin/account/change_password.html', { 'form': form, 'can_change_password': can_change_password, })
def user_password(request): name = _("Update Password") if request.method == 'POST': form = SetPasswordForm(request.user, request.POST) if form.is_valid(): form.save() messages.success(request, _("Password successfully updated.")) return HttpResponseRedirect(reverse('home')) else: # The form is invalid messages.error( request, _("Please correct the errors in the form.")) return render(request, 'djmongo/console/generic/bootstrapform.html', {'form': form, 'name': name, }) # this is a GET context = {'name': name, 'form': SetPasswordForm(user=request.user) } return render(request, 'djmongo/console/generic/bootstrapform.html', context)
def new_password(request, activation_key): """ Display form for recovering password **Context** set password Form **Template:** :template:`new_password.html` """ try: embigo_user = EmbigoUser.objects.get(activation_key=activation_key) if embigo_user.key_expires > timezone.now() and embigo_user.hash_type == "PASSWORD_HASH": if request.method == 'POST': form = SetPasswordForm(embigo_user.user, request.POST) if form.is_valid(): embigo_user.activation_key = None embigo_user.save() form.save() context = {'message': "Twoje hasło zostało zmienione"} return render(request, 'confirmation.html', context) else: form = SetPasswordForm(embigo_user.user) context = {'form': form} return render(request, 'new_password.html', context) else: context = {'message': "Błąd, podany link jest nieaktywny."} except ObjectDoesNotExist: context = {'message': "Błąd, podany link jest nieaktywny."} return render(request, 'confirmation.html', context)
def password_reset_confirm(request, uidb36=None, token=None): """ View that checks the hash in a password reset link and presents a form for entering a new password. """ assert uidb36 is not None and token is not None # checked by URLconf post_reset_redirect = reverse('django.contrib.auth.views.password_reset_complete') try: uid_int = base36_to_int(uidb36) user = User.objects.get(pk=uid_int) except (ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and default_token_generator.check_token(user, token): validlink = True if request.method == 'POST': form = SetPasswordForm(user, request.POST) if form.is_valid(): form.save() return JsonResponse({'status': True, 'redirect': post_reset_redirect}) else: status = False else: form = SetPasswordForm(None) status = True else: raise Http404 context = {'form': form, 'validlink': validlink, 'uidb36': uidb36, 'token': token} if request.is_ajax(): return JsonResponse({'status': status, 'template': render_to_string( 'account/password_reset/confirm_form.html', context, context_instance=RequestContext(request))}) return TemplateResponse(request, 'account/password_reset/confirm_container.html', context)
def change_password(request): if not password_management_enabled(): raise Http404 can_change_password = request.user.has_usable_password() if can_change_password: if request.POST: form = SetPasswordForm(request.user, request.POST) if form.is_valid(): form.save() update_session_auth_hash(request, form.user) messages.success(request, _("Your password has been changed successfully!")) return redirect('wagtailadmin_account') else: form = SetPasswordForm(request.user) else: form = None return render(request, 'wagtailadmin/account/change_password.html', { 'form': form, 'can_change_password': can_change_password, })
def change_pass(request): try: if request.method == "GET": fb = fb_utils.FBConnect(request.GET.get('code', ''), change_pass) if fb.userid != request.user.fbprofile.fb_userid: messages.error(request, "Your facebook account did not" +\ " match the one registered with LitHub.") return redirect('bookswap.views.my_account') request.session['fb_password_uuid'] = str(uuid4()) form = SetPasswordForm(user=request.user) post_uuid = request.POST.get('uuid', '') if request.method=="POST" and post_uuid and \ post_uuid == request.session["fb_password_uuid"]: form = SetPasswordForm(request.user, request.POST) if form.is_valid(): form.save() request.session['fb_password_uuid'] = "" messages.success(request, "Your password was "+\ "successfully changed.") return redirect("bookswap.views.my_account") return render(request, "fbconnect/password_change.html", {'form':form, 'uuid':request.session["fb_password_uuid"]},) except ObjectDoesNotExist: messages.error(request, "Your facebook account was not recognized.") except ValueError: messages.error(request, "There was an error getting your " +\ "information from facebook.") return redirect('bookswap.views.my_account')
class Edit(generic.edit.UpdateView): """ User profile editing """ template_name = 'identity/edit.html' form_class = UserEditForm success_url = reverse_lazy('homepage') model = Identity @method_decorator(never_cache) @method_decorator(login_required) def dispatch(self, request, *args, **kwargs): return super(Edit, self).dispatch(request, *args, **kwargs) def get(self, request, *args, **kwargs): self.password_form = SetPasswordForm(user=request.user) return super(Edit, self).get(request, *args, **kwargs) def post(self, request, *args, **kwargs): self.object = self.get_object() forms_valid = True change_password = False form = self.get_form(self.get_form_class()) if not form.is_valid(): forms_valid = False if self.request.POST.get('new_password1'): change_password = True self.password_form = SetPasswordForm( data=request.POST, user=request.user) if not self.password_form.is_valid(): forms_valid = False else: self.password_form = SetPasswordForm(user=request.user) if forms_valid: form.save() if change_password: self.password_form.save() self.notifications_form.save() return HttpResponseRedirect(self.get_success_url()) else: return self.render_to_response( self.get_context_data(form=form)) def get_object(self): return self.request.user def get_context_data(self, **kwargs): return super(Edit, self).get_context_data( password_form=self.password_form, notifications_form=self.notifications_form, **kwargs )
def test_success(self, password_changed): user = User.objects.get(username="******") data = {"new_password1": "abc123", "new_password2": "abc123"} form = SetPasswordForm(user, data) self.assertTrue(form.is_valid()) form.save(commit=False) self.assertEqual(password_changed.call_count, 0) form.save() self.assertEqual(password_changed.call_count, 1)
def password_reset_confirm(request): if settings.DISABLE_SIGNUP: return HttpResponseRedirect(settings.LOGIN_URL) verification_key = None email_address = None if 'verification_key' in request.GET and request.GET['verification_key']: verification_key = request.GET['verification_key'].replace(' ', '') if 'email_address' in request.GET and request.GET['email_address']: email_address = request.GET['email_address'].replace(' ', '') # Note: all validation errors return the same error message to # avoid leaking information as to the existence or not of # particular email addresses on the system if not verification_key or not email_address: return render_to_response('account/reset_invalidparams.html', context_instance=RequestContext(request)) if len(verification_key) < 64 or len(verification_key) > 64 or len(email_address) < 3: return render_to_response('account/reset_invalidparams.html', context_instance=RequestContext(request)) try: email = ConfirmedEmail.objects.get(email=email_address) except ConfirmedEmail.DoesNotExist: return render_to_response('account/reset_invalidparams.html', context_instance=RequestContext(request)) user = email.user if user.password == u'!': # no password is set, cannot reset it return render_to_response('account/reset_invalidparams.html', context_instance=RequestContext(request)) expected_key = password_reset_key(user) if verification_key != expected_key: return render_to_response('account/reset_invalidparams.html', context_instance=RequestContext(request)) if request.method == 'POST': form = SetPasswordForm(user, request.POST) if form.is_valid(): form.save() return render_to_response('account/password_change_done.html', context_instance=RequestContext(request)) else: form = SetPasswordForm(user) return render_to_response('account/password_change.html', {'form': form, 'verification_key': verification_key, 'email_address': email_address }, context_instance=RequestContext(request))
def post(self,request): if request.user.is_authenticated(): return HttpResponseRedirect('/') form = SetPasswordForm(data=request.POST) if form.is_valid(): form.save() HttpResponseRedirect('/') return render_to_response('registration/set_password_form.html', {'form':form}, context_instance=RequestContext(request))
def set_password(request, id): user = get_object_or_404(User, pk=id) if request.method == "POST": form = SetPasswordForm(user, request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse("manage_users")) else: form = SetPasswordForm(user) return render(request, "app/set_password.html", {"form": form, "this_user": user})
def password_reset_confirm(request, key): template_name = 'accounts/password_reset_confirm.html' context = {} reset = get_object_or_404(PasswordReset, key=key) form = SetPasswordForm(user=reset.user, data=request.POST or None) # Formulário sem a solicitação de senha antiga. if form.is_valid(): form.save() context['success'] = True context['form'] = form return render(request, template_name, context)
def password_reset_confirm(request, key): template_name = "accounts/password_reset_confirm.html" context = {} reset = get_object_or_404(PasswordReset, key=key) form = SetPasswordForm(user=reset.user, data=request.POST or None) if form.is_valid(): form.save() context["success"] = True context["form"] = form return render(request, template_name, context)
def set_password(request): if request.user.has_usable_password(): raise Http404 form = SetPasswordForm(request.user, request.POST or None) if form.is_valid(): form.save() return redirect('/') return render(request, 'accounts/set_password.html', { 'form': form })
def superuser_change_form_handler(request, user_id): """Process the requests from the group superuser Change Account Settings page for the user selected on the superuser home page. This includes requests from the profile change form and the set password form. Parameters: request - The request object that contains the POST data from the froms. user_id - The ID number of the user that should be represented and modified by the change forms. """ changing_user = User.objects.get(id=user_id) changing_profile = changing_user.get_profile() if request.POST: # Process profile change form if 'profile_input' in request.POST: profile_change_form = UserProfileForm(data=request.POST, instance=changing_profile) if profile_change_form.is_valid(): profile_change_form.save() return HttpResponseRedirect( reverse('confirm_superuser_changes', kwargs={'user_id': user_id}) ) set_password_form = SetPasswordForm(user=changing_user) # Process password change form elif 'password_input' in request.POST: set_password_form = SetPasswordForm(user=changing_user, data=request.POST) if set_password_form.is_valid(): set_password_form.save() return HttpResponseRedirect( reverse('confirm_superuser_changes', kwargs={'user_id': user_id}) ) profile_change_form = FullProfileChangeForm( instance=changing_profile) else: return HttpResponseRedirect( reverse('superuser_change_account_settings', kwargs={'user_id': user_id}) ) else: set_password_form = SetPasswordForm(user=changing_user) profile_change_form = UserProfileForm(instance=changing_profile) return render_to_response('superuser_change_account_settings.html', {'username': changing_user.username, 'set_password_form': set_password_form, 'profile_change_form': profile_change_form, 'auth_url': GIT_AUTH_URL}, context_instance=RequestContext(request))
def test_success(self, password_changed): user = User.objects.get(username='******') data = { 'new_password1': 'abc123', 'new_password2': 'abc123', } form = SetPasswordForm(user, data) self.assertTrue(form.is_valid()) form.save(commit=False) self.assertEqual(password_changed.call_count, 0) form.save() self.assertEqual(password_changed.call_count, 1)
def superuser_change_form_handler(request, user_id): """Process the requests from the group superuser Change Account Settings page for the user selected on the superuser home page. This includes requests from the profile change form and the set password form. Parameters: request - The request object that contains the POST data from the froms. user_id - The ID number of the user that should be represented and modified by the change forms. """ changing_user = User.objects.get(id=user_id) changing_profile = changing_user.get_profile() if request.POST: # Process profile change form if 'profile_input' in request.POST: profile_change_form = UserProfileForm(data=request.POST, instance=changing_profile) if profile_change_form.is_valid(): profile_change_form.save() return HttpResponseRedirect( reverse('confirm_superuser_changes', kwargs={'user_id': user_id})) set_password_form = SetPasswordForm(user=changing_user) # Process password change form elif 'password_input' in request.POST: set_password_form = SetPasswordForm(user=changing_user, data=request.POST) if set_password_form.is_valid(): set_password_form.save() return HttpResponseRedirect( reverse('confirm_superuser_changes', kwargs={'user_id': user_id})) profile_change_form = FullProfileChangeForm( instance=changing_profile) else: return HttpResponseRedirect( reverse('superuser_change_account_settings', kwargs={'user_id': user_id})) else: set_password_form = SetPasswordForm(user=changing_user) profile_change_form = UserProfileForm(instance=changing_profile) return render_to_response('superuser_change_account_settings.html', { 'username': changing_user.username, 'set_password_form': set_password_form, 'profile_change_form': profile_change_form, 'auth_url': GIT_AUTH_URL }, context_instance=RequestContext(request))
def change_password(request): usuario = request.user logger.debug('cambiando clave de {}'.format(usuario.username)) if request.method == 'POST': form = SetPasswordForm(usuario, request.POST) if form.is_valid(): form.save() logger.debug('clave cambiada redirigiendo') return redirect('login') else: form = SetPasswordForm(usuario) return render(request, 'change_password.html', {'form': form, })
def set_password(request, pk): user = get_object_or_404(User, id=pk) page_title = "Passwort für User " + user.username + " ändern" if request.method == 'POST': form = SetPasswordForm(user, request.POST) if form.is_valid(): form.save() messages.success(request, 'Das Passwort wurde geändert') else: messages.error(request, 'Fehler') else: form = SetPasswordForm(user) return render(request, 'details.html', {'page_title': page_title, 'forms': [form]})
def password_reset_confirm(request, key): template_name = 'reset/confirm_new_password.html' context = {} reset = get_object_or_404(PasswordReset, key=key) form = SetPasswordForm(user=reset.user, data=request.POST or None) print(form) if form.is_valid(): print('entru') form.save() context['success'] = True context['form'] = form return render(request, template_name, context)
def password(request): if request.user.is_authenticated: if request.method == 'POST': form = SetPasswordForm(data=request.POST, user=request.user) if form.is_valid(): form.save() return redirect('/') else: form = SetPasswordForm(user=request.user) else: return redirect('/portal/') return render(request, 'password.html', {'form': form})
def password_modify(request, user_id): user_obj = User.objects.get(id=user_id) form = SetPasswordForm(user=user_obj) if request.method == "POST": form = SetPasswordForm(user_obj, request.POST) if form.is_valid(): form.save() messages.add_message(request, messages.SUCCESS, u'信息修改成功') return HttpResponseRedirect(reverse('user_list')) return render_to_response("core/password_modify.html", { 'form': form, }, context_instance=RequestContext(request))
def alterar_senha(request): if request.method == "POST": form_senha = SetPasswordForm(request.POST) if form_senha.is_valid(): form_senha.save() messages.add_message(request, messages.INFO, 'Sua senha foi alterada com sucesso!') if request.user.is_authenticated: return redirect('perfil', request.user) else: messages.add_message(request, messages.INFO, 'Realize o login para continuar.') return redirect('home') form_senha = SetPasswordForm() return render(request, 'usuario/alterar-senha.html', {'form_senha': form_senha})
def password_reset_confirm(request, key): template_name = "accounts/password_reset_confirm.html" context = {} reset = get_object_or_404(PasswordReset, key=key) form = SetPasswordForm(user=reset.user, data=request.POST or None) if form.is_valid(): form.save() context["success"] = True context["form"] = form return render(request, template_name, context)
def user_change1(request): if request.user.is_authenticated: if request.method == 'POST': fm = SetPasswordForm(user=request.user, data=request.POST) if fm.is_valid(): fm.save() update_session_auth_hash(request, fm.user) return HttpResponseRedirect('/profile/') else: fm = SetPasswordForm(user=request.user) return render(request, 'change1.html', {'form': fm}) else: return HttpResponseRedirect('/login/')
def post(self, request, user): selected_user = User.objects.filter(id=user).first() form = SetPasswordForm(selected_user, request.POST) if form.is_valid(): form.save() messages.success(request, 'The password was successfully updated') return redirect('priv:user_mgmt') else: messages.error(request, 'Please correct the error below') return render(request, 'hda_privileged/password_reset.html', { 'usr': selected_user, 'form': form })
def change_password(request): if request.method == "POST": form = SetPasswordForm(user=request.user, data=request.POST) if form.is_valid(): form.save() # Updating the password logs out all other sessions for the user # except the current one. update_session_auth_hash(request, form.user) return HttpResponseRedirect('/accounts/profile') else: form = SetPasswordForm(user=request.user) return render(request, 'accounts/change_password.html', {'form': form})
def recover_edit_password(request): if request.method == 'POST': form = SetPasswordForm(recover_password_user, data=request.POST) if form.is_valid(): form.save() return redirect('login') else: form = SetPasswordForm(recover_password_user) return render(request, 'users/recover-edit-password.jinja2', {'form': form})
def post(self, request): form = SetPasswordForm(self.user, request.POST) if form.is_valid(): form.save() self.user.password_reset_token = ( User.password_reset_token.field.get_default()) self.user.password_reset_expiration_date = ( User.password_reset_expiration_date.field.get_default()) self.user.save() LOGGER.info("Password reset successful for %r", self.user) messages.success(request, _("Password was reset successfully.")) return redirect("home") return super().get(request, form=form)
def password_change(request): """This view process the password change of the user, returns Json""" password_form = SetPasswordForm(request.user, request.POST or None) #if form is valid if password_form.is_valid(): #process the form by saving password_form.save() return JsonResponse({'is_changed': True}) else: #else return the error as ajax print password_form.errors return JsonResponse({'is_changed': False, 'reasons': str(password_form.errors)})
def updateAthleteProfile(request, pk): perm = general_methods.control_access(request) if not perm: logout(request) return redirect('accounts:login') user = User.objects.get(pk=pk) directory_user = Athlete.objects.get(user=user) person = Person.objects.get(pk=directory_user.person.pk) communication = Communication.objects.get( pk=directory_user.communication.pk) user_form = DisabledUserForm(request.POST or None, instance=user) person_form = DisabledPersonForm(request.POST or None, request.FILES or None, instance=person) communication_form = DisabledCommunicationForm(request.POST or None, instance=communication) password_form = SetPasswordForm(request.user, request.POST) if request.method == 'POST': if user_form.is_valid() and communication_form.is_valid( ) and person_form.is_valid() and password_form.is_valid(): user.username = user_form.cleaned_data['email'] user.first_name = user_form.cleaned_data['first_name'].upper() user.last_name = user_form.cleaned_data['last_name'].upper() user.email = user_form.cleaned_data['email'] user.set_password(password_form.cleaned_data['new_password1']) user.save() person_form.save() communication_form.save() password_form.save() messages.success(request, 'Sporcu Başarıyla Güncellenmiştir.') return redirect('sbs:sporcu-profil-guncelle') else: messages.warning(request, 'Alanları Kontrol Ediniz ') return render( request, 'sporcu/sporcu-profil-guncelle.html', { 'user_form': user_form, 'communication_form': communication_form, 'person_form': person_form, 'password_form': password_form })
def changepass_view1(request): if request.user.is_authenticated: if request.method == 'POST': fm = SetPasswordForm(user=request.user, data=request.POST) if fm.is_valid(): messages.success(request, 'Password changed successfully !!!') fm.save() update_session_auth_hash(request, fm.user) return HttpResponseRedirect('/profile/') else: fm = SetPasswordForm(user=request.user) return render(request, 'enroll/changepass1.html', {'form': fm}) else: return HttpResponseRedirect('/login/')
def user_Forgot_Password(request): if request.user.is_authenticated: if request.method == 'POST': form = SetPasswordForm(user=request.user, data=request.POST) if form.is_valid(): form.save() update_session_auth_hash(request,form.user) # it is session after change password you stay in profile page messages.success(request,'Password Change Successfully') return HttpResponseRedirect('/profile/') else: form = SetPasswordForm(user=request.user) return render(request,'enroll/forgotpassword.html',{'form':form}) else: return HttpResponseRedirect('/login/')
def user_edit(request, id): action = "Edit" edit_user = get_object_or_404(get_user_model(), id=id) user_form = settings_forms.UserChangeForm(request.POST or None, instance=edit_user) password_form = SetPasswordForm(data=request.POST or None, user=edit_user) if 'user' in request.POST and user_form.is_valid(): user_form.save() messages.success(request, "User information saved.") return redirect('user_list') elif 'password' in request.POST and password_form.is_valid(): password_form.save() messages.success(request, "Password changed.") return redirect('user_list') return render(request, 'administration/user_form.html', locals())
def reset_password(request, code): link = get_object_or_404(PasswordResetLink, code=code, expires__gt=datetime.now()) if request.method == 'POST': form = SetPasswordForm(link.profile.user, request.POST) if form.is_valid(): form.save() link.delete() messages.info(request, MESSAGES['password_reset']) return redirect(login) else: form = SetPasswordForm(link.profile.user) return locals()
def password_set(request): user = request.user if request.method == 'POST': form = SetPasswordForm(user=user, data=request.POST) if form.is_valid(): form.save() update_session_auth_hash(request, form.user) return redirect(reverse('personal_information')) else: form = SetPasswordForm(user=user) context = { 'form': form, } return render(request, 'accounts/password_set.html', context)
def post(self, request, *args, **kwargs): form = SetPasswordForm( request.user, request.POST, label_suffix='', ) if form.is_valid(): form.save() context = self.get_context_data(**kwargs) messages.success(request, 'Password changed.') else: context = self.get_context_data(form=form, **kwargs) context['show_info'], context['show_pas'] = '', 'show active' return self.render_to_response(context)
def c(request): if request.user.is_authenticated: if request.method=="POST": fm=SetPasswordForm(user=request.user,data=request.POST) if fm.is_valid(): fm.save() update_session_auth_hash(request,fm.user) return HttpResponseRedirect('/index/') else: fm=SetPasswordForm(user=request.user) return render(request,'c.html',{'form':fm,'name':request.user}) else: return HttpResponseRedirect('/logi/')
def user_change_pass1(request): if request.user.is_authenticated: if request.method == "POST": fm = SetPasswordForm(user=request.user, data=request.POST) if fm.is_valid(): fm.save() update_session_auth_hash(request, fm.user) messages.success(request, 'Password Changed Successfully ') return HttpResponseRedirect('profile') else: fm = SetPasswordForm(user=request.user) return render(request, 'accounts/change_pass1.html', {'form': fm}) else: return HttpResponseRedirect('/login/')
def passwordReset(request): """ Sets a new password for the user (without needing to know the old password) """ form = SetPasswordForm(user=request.user, data=request.POST or None) if request.method == 'POST': if form.is_valid(): form.save() return redirect(reverse('index')) else: form = SetPasswordForm(user=request.user) return render(request, "reset.html", {"form": form})
def setpassword(request, id): if (request.user.is_authenticated() and request.user.has_perm('pro.add_server')): user = User.objects.get(id=id) if request.method == 'POST': form = SetPasswordForm(user, request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/') form = SetPasswordForm(user) return render_to_response('change_pass.html', {'form': form}, context_instance=RequestContext(request)) errors = "你好像无权访问吧?" return render_to_response('error.html', {'errors': errors})
def password_reset_confirm(request, key): translation.activate('en') template_name = 'password_reset_confirm.html' context = {} reset = get_object_or_404(PasswordReset, key=key) form = SetPasswordForm(user=reset.user, data=request.POST or None) if form.is_valid(): form.save() context['sucess'] = True context['form'] = form return render(request, template_name, context)
def reset_password(request, code): link = get_object_or_404(PasswordResetLink, code=code, expires__gt=datetime.now()) if request.method == 'POST': form = SetPasswordForm(link.profile.user, request.POST) if form.is_valid(): form.save() link.delete() messages.info(request, MESSAGES['password_reset']) return HttpResponseRedirect( reverse('accounts:sign_in_user:sign_in_log_in')) else: form = SetPasswordForm(link.profile.user) return locals()
def password_reset_confirm(request, key): template_name = 'password_change_form.html' context = {} reset = get_object_or_404(PasswordReset, key=key) form = SetPasswordForm(user=reset.user, data=request.POST or None) print(form) if request.method == 'POST': if form.is_valid(): form.save() messages.success(request, 'Senha alterada com sucesso') return redirect('accounts:gate') else: messages.warning(request, form.errors) context['form'] = form return render(request, template_name, context)
def senha_reset_confirmar(request, key): template_name = 'conta/senha_reset_confirmar.html' context = {} reset = get_object_or_404(SenhaReset, key=key) if reset.confirmed == True: context['key_usada'] = True return render(request, template_name, context) form = SetPasswordForm(user=reset.user, data=request.POST or None) if form.is_valid(): reset.confirmed = True reset.save() form.save() context['success'] = True context['form'] = form return render(request, template_name, context)
def change_pass1(request): if request.user.is_authenticated: fm = SetPasswordForm(user=request.user) if request.method == "POST": fm = SetPasswordForm(user=request.user, data=request.POST) if fm.is_valid(): fm.save() update_session_auth_hash(request, fm.user) return redirect("/profile/") else: fm = SetPasswordForm(user=request.user) context = {'forms': fm} return render(request, 'enroll/change_pass1.html', context) else: return redirect("/login/")