예제 #1
0
    def test_clean_with_valid_username_email(self):
        form_data = {'username': '******', 'email': '*****@*****.**'}

        form = SettingsForm(data=form_data,
                            user=self.user,
                            request=self.request)
        form.is_valid()
        form.clean()

        self.assertEqual(form.errors, {})
예제 #2
0
    def test_clean_with_existing_email(self):
        User.objects.create_user(email='*****@*****.**')
        form_data = {'email': '*****@*****.**'}

        form = SettingsForm(data=form_data,
                            user=self.user,
                            request=self.request)
        form.is_valid()
        form.clean()

        self.assertNotEqual(form.errors, {})
예제 #3
0
    def test_save_username(self):
        form_data = {'username': '******'}

        form = SettingsForm(data=form_data,
                            user=self.user,
                            request=self.request)
        form.is_valid()

        user = form.save()

        self.assertEqual(user.username, 'newusername')
예제 #4
0
    def test_save_email(self):
        form_data = {'email': '*****@*****.**'}

        form = SettingsForm(data=form_data,
                            user=self.user,
                            request=self.request)
        form.is_valid()

        user = form.save()

        self.assertEqual(user.email, '*****@*****.**')
예제 #5
0
    def test_save_all_empty_string(self):
        form_data = {'username': '', 'email': '', 'password': ''}

        form = SettingsForm(data=form_data,
                            user=self.user,
                            request=self.request)
        form.is_valid()

        user = form.save()

        self.assertEqual(user.email, self.user.email)
        self.assertTrue(user.check_password('password'))
예제 #6
0
def user_settings(request):
    if request.method == 'POST':
        form = SettingsForm(request.POST, request.FILES)

        if form.is_valid():
            im = Image.open(request.FILES['profile_pic'])
            im = ImageOps.fit(im, (120, 120), Image.ANTIALIAS)

            if not os.path.exists(os.path.join(settings.MEDIA_ROOT,
                                               "profile")):
                os.makedirs(os.path.join(settings.MEDIA_ROOT, "profile"))

            im.save(
                os.path.join(settings.MEDIA_ROOT,
                             "profile/{}.png".format(request.user.netid)))
            request.user.photo = "png"
            request.user.save()

            messages.success(request, 'Votre profil a été mis à jour.')

            return render(request, "users/settings.html",
                          {'form': SettingsForm()})
    else:
        form = SettingsForm()

    return render(request, 'users/settings.html', {
        'form': form,
        'stream': actor_stream(request.user),
    })
예제 #7
0
파일: views.py 프로젝트: UrLab/DocHub
def user_settings(request):
    if request.method == 'POST':
        form = SettingsForm(request.POST, request.FILES)

        if form.is_valid():
            im = Image.open(request.FILES['profile_pic'])
            im = ImageOps.fit(im, (120, 120), Image.ANTIALIAS)

            if not os.path.exists(os.path.join(settings.MEDIA_ROOT, "profile")):
                os.makedirs(os.path.join(settings.MEDIA_ROOT, "profile"))

            im.save(os.path.join(settings.MEDIA_ROOT, "profile/{}.png".format(request.user.netid)))
            request.user.photo = "png"
            request.user.save()

            messages.success(request, 'Ton profil a été mis à jour.')

            return render(request, "users/settings.html", {'form': SettingsForm()})
    else:
        form = SettingsForm()

    token, created = Token.objects.get_or_create(user=request.user)

    return render(request, 'users/settings.html', {
        'form': form,
        'stream': actor_stream(request.user)[:5],
        'token': token,
    })
예제 #8
0
def edit_settings(request):
    """Edit user settings"""
    if request.method == 'POST':
        form = SettingsForm(request.POST)
        if form.is_valid():
            form.save_for_user(request.user)
            messages.add_message(request, messages.INFO,
                                 _(u'Your settings have been saved.'))
            return HttpResponseRedirect(reverse('users.edit_settings'))
        # Invalid form
        return jingo.render(request, 'users/edit_settings.html',
                        {'form': form})

    # Pass the current user's settings as the initial values.
    values = request.user.settings.values()
    initial = dict()
    for v in values:
        try:
            # Uses ast.literal_eval to convert 'False' => False etc.
            # TODO: Make more resilient.
            initial[v['name']] = literal_eval(v['value'])
        except (SyntaxError, ValueError):
            # Attempted to convert the string value to a Python value
            # but failed so leave it a string.
            initial[v['name']] = v['value']
    form = SettingsForm(initial=initial)
    return jingo.render(request, 'users/edit_settings.html',
                        {'form': form})
예제 #9
0
def settings(request):
    user = request.user
    if request.method == 'GET':
        form = SettingsForm(instance=user)
        return render(request,
                      'users/settings.html',
                      context={
                          'form': form,
                          'showed_user': user,
                      })
    elif request.method == 'POST':
        user = request.user
        form = SettingsForm(request.POST, request.FILES, instance=user)
        form.set_user(user)
        if form.is_valid():
            form.image = request.FILES.get('image')
            form.save()
            return redirect(f'/accounts/account/{user.username}')
        else:
            return render(request,
                          'users/settings.html',
                          context={
                              'form': form,
                              'showed_user': user,
                          })
예제 #10
0
def edit_settings(request):
    """Edit user settings"""
    if request.method == 'POST':
        form = SettingsForm(request.POST)
        if form.is_valid():
            form.save_for_user(request.user)
            messages.add_message(request, messages.INFO,
                                 _(u'Your settings have been saved.'))
            return HttpResponseRedirect(reverse('users.edit_settings'))
        # Invalid form
        return jingo.render(request, 'users/edit_settings.html',
                            {'form': form})

    # Pass the current user's settings as the initial values.
    values = request.user.settings.values()
    initial = dict()
    for v in values:
        try:
            # Uses ast.literal_eval to convert 'False' => False etc.
            # TODO: Make more resilient.
            initial[v['name']] = literal_eval(v['value'])
        except (SyntaxError, ValueError):
            # Attempted to convert the string value to a Python value
            # but failed so leave it a string.
            initial[v['name']] = v['value']
    form = SettingsForm(initial=initial)
    return jingo.render(request, 'users/edit_settings.html', {'form': form})
예제 #11
0
 def post(self, request):
     postData = request.POST
     
     settingsForm = SettingsForm(postData)
     settingsForm.user = request.user
     
     if settingsForm.is_valid():
         cleanedData = settingsForm.cleaned_data
         
         username = cleanedData['username']
         email = cleanedData['email']
         firstName = cleanedData['first_name']
         lastName = cleanedData['last_name']
         timezone = cleanedData['timezone']
         gender = cleanedData['gender']
         about = cleanedData['about']
         password = cleanedData['password']
         newPassword1 = cleanedData['new_password1']
         newPassword2 = cleanedData['new_password2']
         
         with transaction.atomic():
             user = request.user
             
             if password or newPassword1 or newPassword2:
                 user.set_password(newPassword1)
                 user.save()
                 
                 user = authenticate(
                     username=user.username,
                     password=newPassword1,
                 )
                 
                 assert user is not None
                 
                 login(request, user)
                 
             userProfile = user.userprofile
             
             user.username = username
             user.email = email
             user.first_name = firstName
             user.last_name = lastName
             
             userProfile.timezone = timezone
             userProfile.about = about
             userProfile.gender = gender
             
             user.save()
             userProfile.save()
             
         return redirect('users_profile', username=username)
         
     else:
         context = {
             'settingsForm'  :   settingsForm,
         }
         
         return render(request, self.template_name, context)
         
         
예제 #12
0
    def test_view_activities(self):
        from users.forms import SettingsForm
        from users.models import Setting

        request = self.factory.get(reverse('lets'))
        request.user = self.u
        views.activities(request)

        eq_('lets', Setting.get_for_user(self.u, 'home_tab'))

        form = SettingsForm(data={'home_tab': 'stream'})
        form.is_valid()
        form.save_for_user(request.user)
        eq_('stream', Setting.get_for_user(self.u, 'home_tab'))

        views.activities(request)
        eq_('lets', Setting.get_for_user(self.u, 'home_tab'))
예제 #13
0
def activities(request, category=None, home_tab=None):
    search_lets = get_relevant_lets(
        request.user, page=request.GET.get('page'),
        category=request.GET.get('category'))
    pages = paginate(request, search_lets['ids'], lcs.LETS_PER_PAGE)
    data = {'lets': search_lets['results'], 'catg': CATEGORY_CHOICES,
            'pages': pages, 'profile': request.user.profile}

    if not home_tab:
        from users.models import Setting
        home_tab = Setting.get_for_user(request.user, 'home_tab')
        if home_tab != 'lets':
            from users.forms import SettingsForm
            form = SettingsForm(data={'home_tab': 'lets'})
            form.is_valid()
            form.save_for_user(request.user)

    return jingo.render(request, 'lets/activities.html', data)
예제 #14
0
    def post(self, request):
        context = self.get_context_data()
        context["settingsform"] = SettingsForm(instance=request.user)
        context["avatarform"] = AvatarForm(instance=request.user)
        context['settingsform'].fields["main_department"].queryset = self.request.user.departments.all()

        if "language" in request.POST:
            request.user.language = request.POST["language"]
            request.user.save()
            translation.activate(request.POST["language"])
            request.session[translation.LANGUAGE_SESSION_KEY] = request.POST["language"]
            return HttpResponseRedirect(reverse("usersettings"))
        elif "pagelength" in request.POST or "timezone" in request.POST:
            form = SettingsForm(request.POST)
            if form.is_valid():
                if request.user.pagelength != form.cleaned_data["pagelength"]:
                    request.user.pagelength = form.cleaned_data["pagelength"]
                    request.user.save()
                if request.user.timezone != form.cleaned_data["timezone"]:
                    request.user.timezone = form.cleaned_data["timezone"]
                    request.user.save()
                if request.user.main_department != form.cleaned_data["main_department"]:
                    request.user.main_department = form.cleaned_data["main_department"]
                    request.user.save()
                messages.success(self.request, _('Settings were successfully updated'))
            context["settingsform"] = form
        elif "avatar" in request.FILES or "avatar" in request.POST:
            if request.user.avatar:
                tempavatar = request.user.avatar
            else:
                tempavatar = None
            form = AvatarForm(request.POST, request.FILES, instance=request.user)
            if form.is_valid():
                if form.cleaned_data["avatar_clear"] and request.user.avatar != None:
                    request.user.avatar.delete()
                    request.user.avatar = None
                    request.user.save()
                if tempavatar != None:
                    tempavatar.storage.delete(tempavatar)
                form.save()
            context["avatarform"] = form
        return render(request, self.template_name, context)
예제 #15
0
def settings(request):
  logging.info("** users.views.settings ")
  user = request.user
  form = SettingsForm(instance=request.user)
  if request.method == 'POST':
    form = SettingsForm(request.POST, instance=request.user)
    if form.is_valid():
      user_ref = form.save()
      avatar = request.FILES.get('avatarfield')
      if avatar is not None:
        user_ref.create_avatar(avatar)
      util.set_flash(request, "success_users_settings")
      return redirect(reverse('users_settings'))
      
  c = template.RequestContext(request, locals())
  return render_to_response('users_settings.html', c)
예제 #16
0
class UserSettingsView(TemplateView):
    template_name = 'users/settings.html'

    @method_decorator(login_required)
    def dispatch(self, request, *args, **kwargs):
        action = request.POST.get('action')
        self.profile_form = SettingsForm(
            (request.POST if action == 'profile' else None),
            (request.FILES if action == 'profile' else None),
            prefix='profile', instance=request.user
        )
        self.password_form = UserPasswordChangeForm(request.user, (request.POST if action == 'password' else None),
                                                    prefix='password')
        self.email_form = UserEmailChangeForm(request.user, (request.POST if action == 'email' else None),
                                              prefix='email')
        return super(UserSettingsView, self).dispatch(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(UserSettingsView, self).get_context_data(**kwargs)
        context['profile_form'] = self.profile_form
        context['password_form'] = self.password_form
        context['email_form'] = self.email_form
        return context

    def post(self, request, *args, **kwargs):
        if self.profile_form.is_valid():
            self.profile_form.save()
            messages.success(request, _(u'Profile success update.'))
            return redirect(request.path)
        elif self.password_form.is_valid():
            self.password_form.save()
            request.user.backend = request.session[BACKEND_SESSION_KEY]
            login(request, request.user)
            messages.success(request, _(u'Password success update.'))
            return redirect(request.path)
        elif self.email_form.is_valid():
            self.email_form.save()
            messages.success(request, _(u'Email success update.'))
            return redirect(request.path)
        return self.get(request, *args, **kwargs)
예제 #17
0
def home(request, note=""):
    """ The settings page for users
    
    If you post a SettingsForm to this, it will be saved. In all cases, it renders index.html to provide the user some
    account managment things.
    
    This view may also take a note, in which case the note will be displayed at the top of the page and the request
    will run as if it were a GET.
    """
    if request.method == "POST" and not note:
        form = SettingsForm(request.POST, instance=request.user.settings)
        if form.is_valid():
            form.save()
            note = "Settings Updated Successfully"
        
    else:
        form = SettingsForm(instance=request.user.settings)
    
    ctx = _make_context(request, "settings_form", form)
    ctx["note"] = note
    
    return TemplateResponse(request, "users/index.html", ctx)
예제 #18
0
파일: views.py 프로젝트: UrLab/DocHub
def user_settings(request):
    if request.method == "POST":
        form = SettingsForm(request.POST, request.FILES)

        if form.is_valid():
            im = Image.open(request.FILES["profile_pic"])
            im = ImageOps.fit(im, (120, 120), Image.ANTIALIAS)

            if not os.path.exists(os.path.join(settings.MEDIA_ROOT, "profile")):
                os.makedirs(os.path.join(settings.MEDIA_ROOT, "profile"))

            im.save(os.path.join(settings.MEDIA_ROOT, "profile/{}.png".format(request.user.netid)))
            request.user.photo = "png"
            request.user.save()

            messages.success(request, "Votre profil a été mis à jour.")

            return render(request, "users/settings.html", {"form": SettingsForm()})
    else:
        form = SettingsForm()

    return render(request, "users/settings.html", {"form": form, "stream": actor_stream(request.user)})
예제 #19
0
    def post(self, request):
        context = self.get_context_data()
        context["settingsform"] = SettingsForm(instance=request.user)
        context["avatarform"] = AvatarForm(instance=request.user)
        context['settingsform'].fields[
            "main_department"].queryset = self.request.user.departments.all()

        # handle language settings and use saved settings of user as default
        if "language" in request.POST:
            request.user.language = request.POST["language"]
            request.user.save()
            translation.activate(request.POST["language"])
            request.session[
                translation.LANGUAGE_SESSION_KEY] = request.POST["language"]
            return HttpResponseRedirect(reverse("usersettings"))

        # handle pagelength/ timezone/ theme settings and use saved settings of user as default
        elif "pagelength" in request.POST or "timezone" in request.POST or "theme" in request.POST:
            form = SettingsForm(request.POST)
            if form.is_valid():
                changed_data = False

                # change of pagelength settings
                if request.user.pagelength != form.cleaned_data["pagelength"]:
                    request.user.pagelength = form.cleaned_data["pagelength"]
                    changed_data = True

                # change of timezone settings
                if request.user.timezone != form.cleaned_data["timezone"]:
                    request.user.timezone = form.cleaned_data["timezone"]
                    changed_data = True

                # change of main department settings
                if request.user.main_department != form.cleaned_data[
                        "main_department"]:
                    request.user.main_department = form.cleaned_data[
                        "main_department"]
                    changed_data = True

                # change of theme settings
                if request.user.theme != form.cleaned_data["theme"]:
                    request.user.theme = form.cleaned_data["theme"]
                    changed_data = True

                # save changes
                if changed_data:
                    request.user.save()

                # save success message
                messages.success(self.request,
                                 _('Settings were successfully updated'))
            context["settingsform"] = form

        # handle given avatar
        elif "avatar" in request.FILES or "avatar" in request.POST:
            if request.user.avatar:
                tempavatar = request.user.avatar
            else:
                tempavatar = None

            form = AvatarForm(request.POST,
                              request.FILES,
                              instance=request.user)

            if form.is_valid():
                if form.cleaned_data[
                        "avatar_clear"] and request.user.avatar is not None:
                    request.user.avatar.delete()
                    request.user.avatar = None
                    request.user.save()
                if tempavatar is not None:
                    tempavatar.storage.delete(tempavatar)
                form.save()
            context["avatarform"] = form

        return render(request, self.template_name, context)