Python django.contrib.auth.forms.PasswordChangeForm() Examples

The following are 22 code examples of django.contrib.auth.forms.PasswordChangeForm(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.contrib.auth.forms , or try the search function .
Example #1
Source File: views.py    From Ghostwriter with BSD 3-Clause "New" or "Revised" License 11 votes vote down vote up
def profile(request):
    """View function for the user profile, profile.html."""
    # Get the current user's user object
    # user = request.user
    # # Look-up the username in the database
    # current_user_name = User.objects.get(username=user.username)
    # current_user_avatar = UserProfile.objects.get(user=user.id)
    # If ths is a POST, process it as a password update
    if request.method == 'POST':
        form = PasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            user = form.save()
            # This is a VERY important step!
            update_session_auth_hash(request, user)
            messages.success(request,
                             'Your password was successfully updated!',
                             extra_tags='alert-success')
            return redirect('profile')
    else:
        form = PasswordChangeForm(request.user)
    return render(request, 'home/profile.html', {
        'form': form,
        # 'current_user': current_user_name,
        # 'user_avatar': current_user_avatar
    }) 
Example #2
Source File: test_view_password_change.py    From django-beginners-guide with MIT License 7 votes vote down vote up
def test_contains_form(self):
        form = self.response.context.get('form')
        self.assertIsInstance(form, PasswordChangeForm) 
Example #3
Source File: views.py    From openag-device-software with GNU General Public License v3.0 6 votes vote down vote up
def change_password(request: Request) -> render:
    """Changes password."""
    if request.method == "POST":
        form = PasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            user = form.save()
            update_session_auth_hash(request, user)  # Important!
            messages.success(request, "Your password was successfully updated!")
            return redirect("change_password")
        else:
            messages.error(request, "Please correct the error below.")
    else:
        form = PasswordChangeForm(request.user)
    return render(request, "accounts/change_password.html", {"form": form})


# just for MW demo
# ------------------------------------------------------------------------------ 
Example #4
Source File: views.py    From cryptofolio with GNU General Public License v3.0 6 votes vote down vote up
def change_password(request):
    if request.method == 'POST':
        form = PasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            user = form.save()
            update_session_auth_hash(request, user)
            messages.success(
                request, 'Your password was successfully updated!')
            return redirect('settings')
        else:
            messages.warning(
                request, 'There was an error changing your password!')
    else:
        form = PasswordChangeForm(request.user)

    return render(request, 'change_password.html', {'form': form}) 
Example #5
Source File: account.py    From c3nav with Apache License 2.0 6 votes vote down vote up
def change_password_view(request):
    if request.method == 'POST':
        form = PasswordChangeForm(user=request.user, data=request.POST)
        if form.is_valid():
            form.save()
            login(request, request.user)
            messages.success(request, _('Password successfully changed.'))
            return redirect('editor.users.detail', pk=request.user.pk)

    else:
        form = PasswordChangeForm(user=request.user)

    for field in form.fields.values():
        field.help_text = None

    return render(request, 'editor/account_form.html', {
        'title': _('Change password'),
        'back_url': reverse('site.account'),
        'form': form
    }) 
Example #6
Source File: views.py    From c3nav with Apache License 2.0 6 votes vote down vote up
def change_password_view(request):
    if request.method == 'POST':
        form = PasswordChangeForm(user=request.user, data=request.POST)
        if form.is_valid():
            form.save()
            login(request, request.user)
            messages.success(request, _('Password successfully changed.'))
            return redirect('site.account')
    else:
        form = PasswordChangeForm(user=request.user)

    for field in form.fields.values():
        field.help_text = None

    return render(request, 'site/account_form.html', {
        'title': _('Change password'),
        'back_url': reverse('site.account'),
        'form': form
    }) 
Example #7
Source File: views.py    From NSP with MIT License 6 votes vote down vote up
def change_password_view(request):
    if request.method == 'POST':
        form = PasswordChangeForm(user=request.user, data=request.POST)

        if form.is_valid():
            form.save()
            # so that user does not get logged out, not working as of now.
            # TODO
            update_session_auth_hash(request, form.user)
            return redirect('/account/profile')
        else:
            return redirect('/account/change-password')

    else:
        form = PasswordChangeForm(user=request.user)
        args = {'form': form}
        return render(request, 'accounts/change_password.html', args) 
Example #8
Source File: account.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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.method == 'POST':
            form = PasswordChangeForm(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 = PasswordChangeForm(request.user)
    else:
        form = None

    return TemplateResponse(request, 'wagtailadmin/account/change_password.html', {
        'form': form,
        'can_change_password': can_change_password,
    }) 
Example #9
Source File: views.py    From Bitpoll with GNU General Public License v3.0 5 votes vote down vote up
def account_settings(request):
    password_change_form = PasswordChangeForm(request.user)
    nick_change_form = NickChangeForm(request.user)
    email_change_form = EmailChangeForm(request.user)

    form = request.POST.get('form')
    if form == 'change_pw':
        password_change_form = PasswordChangeForm(request.user, request.POST)
        if password_change_form.is_valid():
            password_change_form.save()
            update_session_auth_hash(request, request.user)
            messages.success(request, _("Password was changed."))
            return redirect('registration_account')
    elif form == 'change_nick':
        nick_change_form = NickChangeForm(request.user, request.POST)
        if nick_change_form.is_valid():
            nick_change_form.save()
            messages.success(request, _('Your nickname is now {}.').format(
                nick_change_form.cleaned_data['nickname']))
            return redirect('registration_account')
    elif form == 'change_email':
        email_change_form = EmailChangeForm(request.user, request.POST)
        if email_change_form.is_valid():
            return _verify_email(request,
                                 email_change_form.cleaned_data['email'])

    return TemplateResponse(request, 'registration/account.html', {
        'password_change_form': password_change_form,
        'nick_change_form': nick_change_form,
        'email_change_form': email_change_form,
        'username': request.user.username,
    }) 
Example #10
Source File: views.py    From Spirit with MIT License 5 votes vote down vote up
def password_change(request):
    form = PasswordChangeForm(
        user=request.user,
        data=post_data(request))
    if is_post(request) and form.is_valid():
        form.save()
        update_session_auth_hash(request, form.user)
        messages.info(request, _("Your password has been changed!"))
        return redirect(reverse('spirit:user:update'))
    return render(
        request=request,
        template_name='spirit/user/profile_password_change.html',
        context={'form': form}) 
Example #11
Source File: views.py    From Cinema with MIT License 5 votes vote down vote up
def profile(request):
    if request.method == "POST":
        userform = UserForm(request.POST, instance=request.user)
        passwordform = PasswordChangeForm(request.user, request.POST)

        error = False
        if userform.has_changed() and userform.is_valid():
            userform.save()
        elif not userform.has_changed():
            userform = UserForm(instance=request.user)
        else:
            error = True

        if passwordform.has_changed() and passwordform.is_valid():
            passwordform.save()
        elif not passwordform.has_changed():
            passwordform = PasswordChangeForm(user=request.user)
        else:
            error = True

        if not error:
            redirect('login')

    else:
        userform = UserForm(instance=request.user)
        passwordform = PasswordChangeForm(user=request.user)

    ctx = {
        'userform': userform,
        'passwordform': passwordform,
    }
    return render(request, 'profile.html', ctx) 
Example #12
Source File: tests_views.py    From django-userena-ce with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_change_password_view(self):
        """ A ``GET`` to the change password view """
        self.client.login(username="john", password="blowfish")
        response = self.client.get(
            reverse("userena_password_change", kwargs={"username": "john"})
        )

        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, "userena/password_form.html")
        self.assertTrue(response.context["form"], PasswordChangeForm) 
Example #13
Source File: views.py    From FIR with GNU General Public License v3.0 5 votes vote down vote up
def user_self_service(request):
    user_fields = []
    if settings.USER_SELF_SERVICE.get('CHANGE_EMAIL', True):
        user_fields.append('email')
    if settings.USER_SELF_SERVICE.get('CHANGE_NAMES', True):
        user_fields.extend(('first_name', 'last_name'))
    if len(user_fields):
        user_form = modelform_factory(User, fields=user_fields)
    else:
        user_form = False
    if settings.USER_SELF_SERVICE.get('CHANGE_PROFILE', True):
        profile_form = modelform_factory(Profile, exclude=('user',))
    else:
        profile_form = False
    if request.method == "POST":
        post_data = request.POST.dict()
        if user_form:
            user_data = {field:post_data[field] for field in user_fields if field in post_data}
            user_form = user_form(user_data, instance=request.user)
            if user_form.is_valid():
                user_form.save()
        if profile_form:
            profile_data = {field:post_data[field] for field in profile_form.base_fields.keys() if field in post_data}
            profile_form = profile_form(profile_data, instance=request.user.profile)
            if profile_form.is_valid():
                profile_form.save()
    else:
        if user_form:
            user_form = user_form(instance=request.user)
        if profile_form:
            profile_form = profile_form(instance=request.user.profile)
    if settings.USER_SELF_SERVICE.get('CHANGE_PASSWORD', True):
        password_form = PasswordChangeForm(request.user)
    else:
        password_form = False
    return render(request, 'user/profile.html', {
        'user_form': user_form,
        'profile_form': profile_form,
        'password_form': password_form
    }) 
Example #14
Source File: views.py    From TWLight with MIT License 5 votes vote down vote up
def get_context_data(self, **kwargs):
        context = super(UserDetailView, self).get_context_data(**kwargs)
        context["language_form"] = SetLanguageForm(user=self.request.user)
        context["password_form"] = PasswordChangeForm(user=self.request.user)
        return context 
Example #15
Source File: views.py    From TWLight with MIT License 5 votes vote down vote up
def get_context_data(self, **kwargs):
        context = super(EditorDetailView, self).get_context_data(**kwargs)
        editor = self.get_object()
        user = self.request.user
        context["editor"] = editor  # allow for more semantic templates
        context["form"] = EditorUpdateForm(instance=editor)
        context["language_form"] = SetLanguageForm(user=user)
        context["email_form"] = UserEmailForm(user=user)
        # Check if the user is in the group: 'coordinators',
        # and add the reminder email preferences form.
        if coordinators in user.groups.all():
            context["coordinator_email_form"] = CoordinatorEmailForm(user=user)

        try:
            if user.editor == editor and not editor.contributions:
                messages.add_message(
                    self.request,
                    messages.WARNING,
                    # fmt: off
                    # Translators: This message is shown on user's own profile page, encouraging them to make sure their information is up to date, so that account coordinators can use the information to judge applications.
                    _("Please <a href='{url}'>update your contributions</a> to Wikipedia to help coordinators evaluate your applications.")
                    .format(
                        url=reverse_lazy(
                        "users:editor_update", kwargs={"pk": editor.pk}
                        )
                    ),
                    # fmt: on
                )
        except Editor.DoesNotExist:
            """
            If the user viewing the site does not have an attached editor
            (which can happen for administrative users), this error will be
            thrown, preventing the user from viewing the site. We don't actually
            want to have a 500 in this case, though; we just want to not add the
            message, and move on.
            """
            pass

        context["password_form"] = PasswordChangeForm(user=user)

        return context 
Example #16
Source File: views.py    From OMS with Apache License 2.0 5 votes vote down vote up
def password_change(request):
    if request.method == 'POST':
        form = PasswordChangeForm(user=request.user, data=request.POST)
        if form.is_valid():
            form.save()
            update_session_auth_hash(request, form.user)
            return HttpResponseRedirect(reverse('app:password_change_done'))
    else:
        form = PasswordChangeForm(user=request.user)
    return render(request, 'password_change.html', {'form':form}) 
Example #17
Source File: views.py    From bitnodes-hardware with MIT License 5 votes vote down vote up
def change_password(request, template='administration/change_password.html',
                    change_password_form=PasswordChangeForm):
    if request.method == 'POST':
        form = change_password_form(user=request.user, data=request.POST)
        if form.is_valid():
            form.save()
            update_session_auth_hash(request, form.user)
            messages.success(request, 'Password updated.')
            return HttpResponseRedirect(resolve_url('administration'))
    else:
        form = change_password_form(user=request.user)
    context = {
        'form': form,
    }
    return render(request, template, context) 
Example #18
Source File: views.py    From AutoGrader with MIT License 5 votes vote down vote up
def change_password(request):
    if request.method == 'POST':
        form = PasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            user = form.save()
            update_session_auth_hash(request, user)  # Important!
            messages.success(request, 'Your password was successfully updated!')
            return redirect('/autograde')
    else:
        form = PasswordChangeForm(request.user)
    return render(request, 'account/change_password.html', {
        'form': form
    }) 
Example #19
Source File: user.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def change_password(self, params):
        """Update the authenticated user password."""
        form = PasswordChangeForm(user=self.user, data=get_QueryDict(params))
        if form.is_valid():
            form.save()
            self.user.sshkeys_count = self.user.sshkey_set.count()
            self.user.machines_count = self.user.node_set.count()
            return self.full_dehydrate(self.user)
        else:
            raise HandlerValidationError(form.errors) 
Example #20
Source File: api.py    From canvas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def change_profile(request, old_password=None, new_password=None, new_email=None, bio=None):
    if bio is not None:
        request.user.userinfo.bio_text = bio
        request.user.userinfo.save()
        request.user.details.force()

    if new_email is not None:
        if not User.validate_email(new_email):
            raise ValidationError({'new_email': "Please enter a valid email address."})

        if request.user.email != new_email:
            if not User.email_is_unused(new_email):
                raise ValidationError({'new_email': "Sorry! That email address is already being used for an account."})

            request.user.email = new_email
            request.user.save()
            request.user.details.force()

    if old_password is not None and new_password is not None:
        if not User.validate_password(new_password):
            raise ValidationError({
                'new_password': "Sorry, your new password is too short. "
                                "Please use {} or more characters.".format(User.MINIMUM_PASSWORD_LENGTH),
            })

        form = PasswordChangeForm(user=request.user, data={
            'old_password': old_password,
            'new_password1': new_password,
            'new_password2': new_password,
        })

        api_forms.validate(form)
        form.save()
        request.user.details.force() 
Example #21
Source File: views.py    From django-bananas with MIT License 5 votes vote down vote up
def create(self, request):
        """
        Change password for logged in django staff user
        """
        # TODO: Decorate api with sensitive post parameters as Django admin do?

        password_form = PasswordChangeForm(request.user, data=request.data)

        if not password_form.is_valid():
            raise serializers.ValidationError(password_form.errors)

        password_form.save()
        update_session_auth_hash(request, password_form.user)

        return Response(status=status.HTTP_204_NO_CONTENT) 
Example #22
Source File: views.py    From FIR with GNU General Public License v3.0 5 votes vote down vote up
def user_change_password(request):
    if not settings.USER_SELF_SERVICE.get('CHANGE_PASSWORD', True):
        messages.error(request, "Error: Password change administratively disabled.")
        return HttpResponseServerError(dumps({'status': 'error', 'errors': ['password change disabled.',]}),
                                       content_type="application/json")
    if request.method == "POST":
        form = PasswordChangeForm(user=request.user, data=request.POST)
        if form.is_valid():
            form.save()
            messages.success(request, "Success! Password updated.")
            return HttpResponse(dumps({'status': 'success'}), content_type="application/json")

    ret = {'status': 'error', 'errors': form.errors}
    messages.error(request, form.errors)
    return HttpResponseServerError(dumps(ret), content_type="application/json")