Esempio n. 1
3
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)
Esempio n. 2
0
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)
Esempio n. 3
0
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)
Esempio n. 4
0
    def resetpassword(self, request):
        uidb64 = self.request.POST.get("uidb64", "")
        token = self.request.POST.get("token", "")
        password1 = self.request.POST.get("password1", "")
        password2 = self.request.POST.get("password2", "")

        try:
            uid = urlsafe_base64_decode(uidb64)
            user = JoklinUser._default_manager.get(pk=uid)
        except (TypeError, ValueError, OverflowError, JoklinUser.DoesNotExist):
            user = None

        token_generator = default_token_generator

        if user is not None and token_generator.check_token(user, token):
            form = SetPasswordForm(user, request.POST)
            errors = []
            if form.is_valid():
                user = form.save()
            else:
                # 如果表单不正确,保存错误到errors列表中
                for k, v in form.errors.items():
                    # v.as_text() 详见django.forms.util.ErrorList 中
                    errors.append(v.as_text())

            mydict = {"errors": errors}
            return HttpResponse(json.dumps(mydict), content_type="application/json")
        else:
            logger.error(u"[UserControl]用户重置密码连接错误:[{}]/[{}]".format(uid64, token))
            return HttpResponse(u"密码重设失败!\n密码重置链接无效,可能是因为它已使用。可以请求一次新的密码重置.", status=403)
Esempio n. 5
0
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,
    })
Esempio n. 6
0
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)
Esempio n. 7
0
    def mutate_and_get_payload(cls, input, request, info):
        errors = []
        UserModel = User._meta.model

        try:
            # urlsafe_base64_decode() decodes to bytestring on Python 3
            uid = force_text(urlsafe_base64_decode(input.get('uidb64')))
            user = UserModel.objects.get(pk=uid)
        except (TypeError, ValueError, OverflowError, UserModel.DoesNotExist):
            user = None

        if user and default_token_generator.check_token(user, input.get('token')):
            form = SetPasswordForm(user=user, data=input)
            if form.is_valid():
                user = form.save(commit=False)
                user.save(request=request)

                # workarout to re authenticate the user
                # when as change the user on the DB it gets disconected
                user.backend = settings.DEFAULT_AUTHENTICATION_BACKENDS
                auth_login(request, user)
            else:
                errors = form_erros(form, errors)
        else:
            errors.append(Error(
                code='password_reset_incorrect_token',
                message=_('Password reset failed')
            ))

        return PasswordResetComplete(errors=errors)
Esempio n. 8
0
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,
    })
Esempio n. 9
0
 def resetpassword(self,request):
     uidb64 = self.request.POST.get("uidb64","")
     token = self.request.POST.get("token","")
     password1 = self.request.POST.get("password1","")
     password2 = self.request.POST.get("password2","")
     
     try:
         uid = urlsafe_base64_decode(uidb64)
         user = User.objects.get(id=uid)
     except (TypeError,ValueError,OverflowError,User.DoesNotExist):
         user = None
     
     token_generator  = default_token_generator
     if user is not None and token_generator.check_token(user,token):
         form = SetPasswordForm(user,request.POST)
         error = []
         if form.is_valid():
             user = form.save()
         else:
             #如果表单不正确,保存错误到errors列表中
             for k,v in form.errors.items():
                 errors.append(v.as_text())
                 
     else:
         return HttpResponse("密码重设失败!\n密码重置链接无效,可能因为它已使用。可以请求一次新的密码重设.",status=403)
Esempio n. 10
0
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')
Esempio n. 11
0
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)
Esempio n. 12
0
 def test_password_whitespace_not_stripped(self):
     user = User.objects.get(username="testclient")
     data = {"new_password1": "   password   ", "new_password2": "   password   "}
     form = SetPasswordForm(user, data)
     self.assertTrue(form.is_valid())
     self.assertEqual(form.cleaned_data["new_password1"], data["new_password1"])
     self.assertEqual(form.cleaned_data["new_password2"], data["new_password2"])
Esempio n. 13
0
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)
Esempio n. 14
0
    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)
Esempio n. 15
0
    def post(self, request, *args, **kwargs):
        """
        request associate profile

        """
        response_data = {}
        response_data['status'] = True
        if request.is_ajax():
            user_id = request.POST.get('user_id')
            try:
                if request.POST.get('associate'):
                    user = User.objects.get(id=user_id)
                else:
                    store_user = StoreAccountProfile.objects.get(id=user_id)
                    user = User.objects.get(id=store_user.user.id)
                password_form = SetPasswordForm(user, request.POST)
                if password_form.is_valid():
                    password = password_form.cleaned_data.get('new_password1')
                    user.set_password(password)
                    user.save()
                else:
                    response_data['status'] = False
                    response_data['errors'] = password_form.errors
            except User.DoesNotExist:
                response_data['status'] = False
            return HttpResponse(json.dumps(response_data), content_type="application/json")
Esempio n. 16
0
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,
    })
Esempio n. 17
0
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
            }
Esempio n. 18
0
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)
Esempio n. 19
0
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')
Esempio n. 20
0
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)
Esempio n. 21
0
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())
Esempio n. 22
0
def reset_password_new_user(request, uidb36, token):
    """
    Checks the link the user clicked and prompts for a new password
    :param request: the standard request given by Django
    :param uidb36: the id's hash
    :param token: token created dynamically
    """
    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 not user.has_usable_password() \
        and default_token_generator.check_token(user, token):
        validlink = True
        if request.method == "POST":
            form = SetPasswordForm(user, request.POST)
            if form.is_valid():
                user = form.save()
                user.is_active = True
                user.save()
                user.backend = 'django.contrib.auth.backends.ModelBackend'
                login(request, user)
                return HttpResponseRedirect(reverse('index'))
        else:
            form = SetPasswordForm(None)
    else:
        validlink = False
        form = None
    return render(request, 'registration/reset_password_complete.html', {
        'form': form,
        'validlink': validlink
    })
Esempio n. 23
0
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)
Esempio n. 24
0
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
    })
Esempio n. 25
0
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)
Esempio n. 26
0
 def test_password_verification(self):
     # The two new passwords do not match.
     user = User.objects.get(username="testclient")
     data = {"new_password1": "abc123", "new_password2": "abc"}
     form = SetPasswordForm(user, data)
     self.assertFalse(form.is_valid())
     self.assertEqual(form["new_password2"].errors, [force_unicode(form.error_messages["password_mismatch"])])
Esempio n. 27
0
def reset_password(request, hash):
    """Perform a password change.
    
    If the request method is set to GET and the hash matches a form 
    will be displayed to the user allowing the password change.
    If the request method is POST the user password will be changed
    to the newly set data.
    
    """

    profile = get_object_or_404(UserProfile, verification_hash=hash)
    user = profile.user

    form = SetPasswordForm(profile.user)

    template_data = {"form": form, "hash": hash}

    if request.method == "GET":
        return render_to_response("account_change_password.html", template_data, RequestContext(request))

    form = SetPasswordForm(user, request.POST)
    template_data.update({"form": form})

    if not form.is_valid():
        return render_to_response("account_change_password.html", template_data, RequestContext(request))

    profile.verification_hash = "verified"
    profile.save()

    user.set_password(form.cleaned_data.get("new_password1"))
    user.save()

    template_data.update({"msg": _(u"Password changed successfully!"), "msg_css_class": "success"})
    return render_to_response("account_message.html", template_data, RequestContext(request))
Esempio n. 28
0
    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))
Esempio n. 29
0
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
        )
Esempio n. 30
0
 def test_success(self):
     user = User.objects.get(username='testclient')
     data = {
         'new_password1': 'abc123',
         'new_password2': 'abc123',
         }
     form = SetPasswordForm(user, data)
     self.assertTrue(form.is_valid())