Example #1
0
def edit_avatar(request):
    """Edit user avatar."""
    try:
        user_profile = request.user.get_profile()
    except Profile.DoesNotExist:
        # TODO: Once we do user profile migrations, all users should have a
        # a profile. We can remove this fallback.
        user_profile = Profile.objects.create(user=request.user)

    if request.method == 'POST':
        # Upload new avatar and replace old one.
        old_avatar_path = None
        if user_profile.avatar:
            # Need to store the path, not the file here, or else django's
            # form.is_valid() messes with it.
            old_avatar_path = user_profile.avatar.path
        form = AvatarForm(request.POST, request.FILES, instance=user_profile)
        if form.is_valid():
            if old_avatar_path:
                os.unlink(old_avatar_path)
            user_profile = form.save()

            # Delete uploaded avatar and replace with thumbnail.
            name = user_profile.avatar.name
            user_profile.avatar.delete()
            user_profile.avatar.save(name, content, save=True)
            return HttpResponseRedirect(reverse('users.edit_profile'))

    else:  # request.method == 'GET'
        form = AvatarForm(instance=user_profile)

    return render(request, 'users/edit_avatar.html',
                  {'form': form, 'profile': user_profile})
Example #2
0
def upload_avatar(request):
    ''' Upload an Avatar '''
    next = urlparse(request.GET.get('next'))
    role = resolve(next.path).app_name
    request = userApi.has_users_view_access(request, role)

    if request.method == 'POST':
        if len(request.FILES) == 0:
            messages.error(request, 'An error occurred. Please select your profile photo, then try again.')
            return HttpResponseRedirect(request.get_full_path())

        form = AvatarForm(request.POST, request.FILES)
        if form.is_valid():
            avatar = form.save(commit=False)
            avatar.uploaded = request.FILES.get('uploaded')
            avatar.save()
            if avatar:
                messages.success(request, 'Success! Profile Photo uploaded.')
            else:
                messages.error(request, 'An error occurred while uploading an avatar.')
        else:
            errors = form.errors.get_json_data()
            messages.error(request, 'An error occurred. Form is invalid. {0}'.format( userApi.get_error_messages(errors) ))

        return HttpResponseRedirect(request.get_full_path())

    return render(request, 'users/upload_avatar.html', {
        'loggedin_user': userApi.add_avatar(request.user),
        'role': role,
        'form': AvatarForm(initial={ 'user': request.user })
    })
Example #3
0
 def post(self, request, username):
     form = AvatarForm(request.POST, request.FILES)
     if form.is_valid():
         profile = Profile.objects.get(user=request.user)
         profile.avatar = form.cleaned_data['avatar']
         profile.save()
     return HttpResponseRedirect(
         reverse('users:detail', kwargs={'username': username}))
Example #4
0
def edit_avatar(request):
    """Edit user avatar."""
    try:
        user_profile = request.user.get_profile()
    except Profile.DoesNotExist:
        # TODO: Once we do user profile migrations, all users should have a
        # a profile. We can remove this fallback.
        user_profile = Profile.objects.create(user=request.user)

    if request.method == 'POST':
        # Upload new avatar and replace old one.
        old_avatar_path = None
        if user_profile.avatar:
            # Need to store the path, not the file here, or else django's
            # form.is_valid() messes with it.
            old_avatar_path = user_profile.avatar.path
        form = AvatarForm(request.POST, request.FILES, instance=user_profile)
        if form.is_valid():
            if old_avatar_path:
                os.unlink(old_avatar_path)
            user_profile = form.save()

            content = _create_image_thumbnail(user_profile.avatar.path,
                                              settings.AVATAR_SIZE)
            # Delete uploaded avatar and replace with thumbnail.
            name = user_profile.avatar.name
            user_profile.avatar.delete()
            user_profile.avatar.save(name, content, save=True)
            return HttpResponseRedirect(reverse('users.edit_profile'))

    else:  # request.method == 'GET'
        form = AvatarForm(instance=user_profile)

    return jingo.render(request, 'users/edit_avatar.html',
                        {'form': form, 'profile': user_profile})
Example #5
0
def upload_avatar(request):
    if not request.method == "POST":
        form = AvatarForm()
    else:
        form = AvatarForm(request.POST, request.FILES)
        if form.is_valid():
            image = form.cleaned_data.get('photo')
            avatar = Avatar(user=request.user, image=image, valid=True)
            avatar.image.save("%s.jpg" % request.user.username, image)
            image = Image.open(avatar.image.path)
            image.thumbnail((480, 480), Image.ANTIALIAS)
            image.convert("RGB").save(avatar.image.path, "JPEG")
            avatar.save()
            return HttpResponseRedirect('/home/')

    if DEFAULT_AVATAR:
        base, filename = os.path.split(DEFAULT_AVATAR)
        filename, extension = os.path.splitext(filename)
        generic96 = "%s/%s.96%s" % (base, filename, extension)
        generic96 = generic96.replace(settings.MEDIA_ROOT, settings.MEDIA_URL)
    else:
        generic96 = ""

    return HttpResponse(generic96)
Example #6
0
    def get_context_data(self, **kwargs):
        # Call the base implementation first to get a context
        context = super(UsersettingsView, self).get_context_data(**kwargs)
        # Add in a QuerySet of all the books
        if self.request.method != "POST":
            context['settingsform'] = SettingsForm(instance=self.request.user)
            context['avatarform'] = AvatarForm(instance=self.request.user)

        if "settingsform" in context:
            context['settingsform'].fields[
                "main_department"].queryset = self.request.user.departments.all(
                )

        # adds "Settings" to breadcrumbs
        context["breadcrumbs"] = [(reverse("userprofile",
                                           kwargs={"pk": self.request.user.pk
                                                   }), self.request.user),
                                  ("", _("Settings"))]

        return context
Example #7
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)