Exemple #1
0
 def _get_organization_url(organization):
     """calculates url to the organization based on its id and name"""
     organization_slug = slugify(organization["name"])
     return reverse(
         "organization_detail",
         kwargs={"organization_id": organization["id"], "organization_slug": organization_slug},
     )
Exemple #2
0
 def _get_organization_url(organization):
     """calculates url to the organization based on its id and name"""
     organization_slug = slugify(organization['name'])
     return reverse('organization_detail',
                    kwargs={
                        'organization_id': organization['id'],
                        'organization_slug': organization_slug
                    })
Exemple #3
0
    def clean(self, username):
        """ validate username """
        if self.skip_clean == True:
            logging.debug('username accepted with no validation')
            return username
        if self.user_instance is None:
            pass
        elif isinstance(self.user_instance, User):
            if username == self.user_instance.username:
                logging.debug('username valid')
                return username
        else:
            raise TypeError('user instance must be of type User')

        try:
            username = super(UserNameField, self).clean(username)
        except forms.ValidationError:
            raise forms.ValidationError(self.error_messages['required'])

        username_re_string = const.USERNAME_REGEX_STRING
        #attention: here we check @ symbol in two places: input and the regex
        if openode_settings.ALLOW_EMAIL_ADDRESS_IN_USERNAME is False:
            if '@' in username:
                raise forms.ValidationError(self.error_messages['noemail'])

            username_re_string = username_re_string.replace('@', '')

        username_regex = re.compile(username_re_string, re.UNICODE)

        if self.required and not username_regex.search(username):
            raise forms.ValidationError(self.error_messages['invalid'])
        if username in self.RESERVED_NAMES:
            raise forms.ValidationError(self.error_messages['forbidden'])
        if slugify(username) == '':
            raise forms.ValidationError(self.error_messages['meaningless'])
        try:
            user = self.db_model.objects.get(
                **{'%s' % self.db_field: username})
            if user:
                if self.must_exist:
                    logging.debug(
                        'user exists and name accepted b/c here we validate existing user'
                    )
                    return username
                else:
                    raise forms.ValidationError(self.error_messages['taken'])
        except self.db_model.DoesNotExist:
            if self.must_exist:
                logging.debug('user must exist, so raising the error')
                raise forms.ValidationError(self.error_messages['missing'])
            else:
                logging.debug('user name valid!')
                return username
        except self.db_model.MultipleObjectsReturned:
            logging.debug('error - user with this name already exists')
            raise forms.ValidationError(self.error_messages['multiple-taken'])
Exemple #4
0
    def clean(self, username):
        """ validate username """
        if self.skip_clean == True:
            logging.debug('username accepted with no validation')
            return username
        if self.user_instance is None:
            pass
        elif isinstance(self.user_instance, User):
            if username == self.user_instance.username:
                logging.debug('username valid')
                return username
        else:
            raise TypeError('user instance must be of type User')

        try:
            username = super(UserNameField, self).clean(username)
        except forms.ValidationError:
            raise forms.ValidationError(self.error_messages['required'])

        username_re_string = const.USERNAME_REGEX_STRING
        #attention: here we check @ symbol in two places: input and the regex
        if openode_settings.ALLOW_EMAIL_ADDRESS_IN_USERNAME is False:
            if '@' in username:
                raise forms.ValidationError(self.error_messages['noemail'])

            username_re_string = username_re_string.replace('@', '')

        username_regex = re.compile(username_re_string, re.UNICODE)

        if self.required and not username_regex.search(username):
            raise forms.ValidationError(self.error_messages['invalid'])
        if username in self.RESERVED_NAMES:
            raise forms.ValidationError(self.error_messages['forbidden'])
        if slugify(username) == '':
            raise forms.ValidationError(self.error_messages['meaningless'])
        try:
            user = self.db_model.objects.get(
                    **{'%s' % self.db_field: username}
            )
            if user:
                if self.must_exist:
                    logging.debug('user exists and name accepted b/c here we validate existing user')
                    return username
                else:
                    raise forms.ValidationError(self.error_messages['taken'])
        except self.db_model.DoesNotExist:
            if self.must_exist:
                logging.debug('user must exist, so raising the error')
                raise forms.ValidationError(self.error_messages['missing'])
            else:
                logging.debug('user name valid!')
                return username
        except self.db_model.MultipleObjectsReturned:
            logging.debug('error - user with this name already exists')
            raise forms.ValidationError(self.error_messages['multiple-taken'])
Exemple #5
0
def gravatar(user, size):
    """
    Creates an ``<img>`` for a user's Gravatar with a given size.

    This tag can accept a User object, or a dict containing the
    appropriate values.
    """
    # todo: rewrite using get_from_dict_or_object
    user_id = functions.get_from_dict_or_object(user, "id")
    slug = slugify(user.username)
    user_profile_url = reverse("user_profile", kwargs={"id": user_id, "slug": slug})
    # safe_username = template.defaultfilters.urlencode(username)
    return mark_safe(
        GRAVATAR_TEMPLATE
        % {
            "user_profile_url": user_profile_url,
            "size": size,
            "gravatar_hash": functions.get_from_dict_or_object(user, "gravatar"),
            "gravatar_type": openode_settings.GRAVATAR_TYPE,
            "alt_text": _("%(username)s gravatar image") % {"username": user.username},
            "username": functions.get_from_dict_or_object(user, "username"),
        }
    )
Exemple #6
0
def gravatar(user, size):
    """
    Creates an ``<img>`` for a user's Gravatar with a given size.

    This tag can accept a User object, or a dict containing the
    appropriate values.
    """
    #todo: rewrite using get_from_dict_or_object
    user_id = functions.get_from_dict_or_object(user, 'id')
    slug = slugify(user.username)
    user_profile_url = reverse(
                        'user_profile',
                        kwargs={'id': user_id, 'slug': slug}
                    )
    #safe_username = template.defaultfilters.urlencode(username)
    return mark_safe(GRAVATAR_TEMPLATE % {
        'user_profile_url': user_profile_url,
        'size': size,
        'gravatar_hash': functions.get_from_dict_or_object(user, 'gravatar'),
        'gravatar_type': openode_settings.GRAVATAR_TYPE,
        'alt_text': _('%(username)s gravatar image') % {'username': user.username},
        'username': functions.get_from_dict_or_object(user, 'username'),
    })
Exemple #7
0
 def save(self, *args, **kwargs):
     if not self.slug.strip():
         self.slug = slugify(self.title).replace("_", "-").strip()
     return super(StaticPage, self).save(*args, **kwargs)
Exemple #8
0
 def slug(self):
     return slugify(self.title)
Exemple #9
0
def organization_detail(request, organization_id, organization_slug):
    if not request.user.is_authenticated():
        return render_forbidden(request)

    user_acceptance_level = 'closed'
    user_membership_level = 'none'
    try:
        organization = models.Organization.objects.get(id=organization_id)
        user_acceptance_level = organization.get_openness_level_for_user(
                                                                    request.user
                                                                )
    except models.Organization.DoesNotExist:
        raise Http404

    ################################################################
    # upload organization logo

    logo_form = OrganizationLogoForm(instance=organization)
    if request.method == "POST":
        logo_form = OrganizationLogoForm(request.POST, request.FILES, instance=organization)
        if logo_form.is_valid():
            logo_form.save()
            return HttpResponseRedirect(request.path)

    ################################################################

    if organization_slug == slugify(organization.title):
        users = models.User.objects.exclude(status='b')
        #filter users by full organization memberships
        #todo: refactor as Organization.get_full_members()
        full_level = models.OrganizationMembership.FULL
        memberships = models.OrganizationMembership.objects.filter(
                                        organization=organization, level=full_level
                                    )
        user_ids = memberships.values_list('user__id', flat=True)
        users = users.filter(id__in=user_ids)
        if request.user.is_authenticated():
            membership = request.user.get_organization_membership(organization)
            if membership:
                user_membership_level = membership.get_level_display()

    else:
        organization_page_url = reverse(
                            'organization_detail',
                            kwargs={
                                'organization_id': organization.id,
                                'organization_slug': slugify(organization.title)
                            }
                        )
        return HttpResponseRedirect(organization_page_url)

    sortby = request.GET.get('sort', 'last_name')

    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1

    search_query = request.REQUEST.get('query',  "")
    if search_query == "":
        if sortby == "newest":
            order_by_parameter = ('-date_joined',)
        elif sortby == "last":
            order_by_parameter = ('date_joined',)
        elif sortby == "user":
            order_by_parameter = ('last_name', 'first_name')
        else:
            # default
            order_by_parameter = ('last_name', 'first_name')

        objects_list = Paginator(
                            users.order_by(*order_by_parameter),
                            const.USERS_PAGE_SIZE
                        )
        base_url = request.path + '?sort=%s&amp;' % sortby
    else:
        sortby = "last_name"
        matching_users = models.get_users_by_text_query(search_query, users)
        objects_list = Paginator(
                            matching_users.order_by(*('last_name', 'first_name')),
                            const.USERS_PAGE_SIZE
                        )
        base_url = request.path + '?name=%s&amp;sort=%s&amp;' % (search_query, sortby)

    try:
        users_page = objects_list.page(page)
    except (EmptyPage, InvalidPage):
        users_page = objects_list.page(objects_list.num_pages)

    paginator_data = {
        'is_paginated': bool(objects_list.count > const.USERS_PAGE_SIZE),
        'pages': objects_list.num_pages,
        'page': page,
        'has_previous': users_page.has_previous(),
        'has_next': users_page.has_next(),
        'previous': users_page.previous_page_number(),
        'next': users_page.next_page_number(),
        'base_url': base_url
    }
    paginator_context = functions.setup_paginator(paginator_data)

    #todo: cleanup this branched code after organizations are migrated to auth_organization
    user_organizations = get_organizations().all()
    if len(user_organizations) <= 1:
        user_organizations = None
    organization_openness_choices = models.Organization().get_openness_choices()

    data = {
        'active_tab': 'users',
        'page_class': 'users-page',
        'users': users_page,
        'organization': organization,
        'search_query': search_query,
        'tab_id': sortby,
        'paginator_context': paginator_context,
        'user_acceptance_level': user_acceptance_level,
        'user_membership_level': user_membership_level,
        'user_organizations': user_organizations,
        'organization_openness_choices': organization_openness_choices,
        "logo_form": logo_form,
    }

    return render_into_skin('organization_detail.html', data, request)
Exemple #10
0
 def slug(self):
     return slugify(self.title)
Exemple #11
0
def organization_detail(request, organization_id, organization_slug):
    if not request.user.is_authenticated():
        return render_forbidden(request)

    user_acceptance_level = 'closed'
    user_membership_level = 'none'
    try:
        organization = models.Organization.objects.get(id=organization_id)
        user_acceptance_level = organization.get_openness_level_for_user(
                                                                    request.user
                                                                )
    except models.Organization.DoesNotExist:
        raise Http404

    ################################################################
    # upload organization logo

    logo_form = OrganizationLogoForm(instance=organization)
    if request.method == "POST":
        logo_form = OrganizationLogoForm(request.POST, request.FILES, instance=organization)
        if logo_form.is_valid():
            logo_form.save()
            return HttpResponseRedirect(request.path)

    ################################################################

    if organization_slug == slugify(organization.title):
        users = models.User.objects.exclude(status='b')
        #filter users by full organization memberships
        #todo: refactor as Organization.get_full_members()
        full_level = models.OrganizationMembership.FULL
        memberships = models.OrganizationMembership.objects.filter(
                                        organization=organization, level=full_level
                                    )
        user_ids = memberships.values_list('user__id', flat=True)
        users = users.filter(id__in=user_ids)
        if request.user.is_authenticated():
            membership = request.user.get_organization_membership(organization)
            if membership:
                user_membership_level = membership.get_level_display()

    else:
        organization_page_url = reverse(
                            'organization_detail',
                            kwargs={
                                'organization_id': organization.id,
                                'organization_slug': slugify(organization.title)
                            }
                        )
        return HttpResponseRedirect(organization_page_url)

    sortby = request.GET.get('sort', 'last_name')

    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1

    search_query = request.REQUEST.get('query',  "")
    if search_query == "":
        if sortby == "newest":
            order_by_parameter = ('-date_joined',)
        elif sortby == "last":
            order_by_parameter = ('date_joined',)
        elif sortby == "user":
            order_by_parameter = ('last_name', 'first_name')
        else:
            # default
            order_by_parameter = ('last_name', 'first_name')

        objects_list = Paginator(
                            users.order_by(*order_by_parameter),
                            const.USERS_PAGE_SIZE
                        )
        base_url = request.path + '?sort=%s&amp;' % sortby
    else:
        sortby = "last_name"
        matching_users = models.get_users_by_text_query(search_query, users)
        objects_list = Paginator(
                            matching_users.order_by(*('last_name', 'first_name')),
                            const.USERS_PAGE_SIZE
                        )
        base_url = request.path + '?name=%s&amp;sort=%s&amp;' % (search_query, sortby)

    try:
        users_page = objects_list.page(page)
    except (EmptyPage, InvalidPage):
        users_page = objects_list.page(objects_list.num_pages)

    paginator_data = {
        'is_paginated': bool(objects_list.count > const.USERS_PAGE_SIZE),
        'pages': objects_list.num_pages,
        'page': page,
        'has_previous': users_page.has_previous(),
        'has_next': users_page.has_next(),
        'previous': users_page.previous_page_number(),
        'next': users_page.next_page_number(),
        'base_url': base_url
    }
    paginator_context = functions.setup_paginator(paginator_data)

    #todo: cleanup this branched code after organizations are migrated to auth_organization
    user_organizations = get_organizations().all()
    if len(user_organizations) <= 1:
        user_organizations = None
    organization_openness_choices = models.Organization().get_openness_choices()

    data = {
        'active_tab': 'users',
        'page_class': 'users-page',
        'users': users_page,
        'organization': organization,
        'search_query': search_query,
        'tab_id': sortby,
        'paginator_context': paginator_context,
        'user_acceptance_level': user_acceptance_level,
        'user_membership_level': user_membership_level,
        'user_organizations': user_organizations,
        'organization_openness_choices': organization_openness_choices,
        "logo_form": logo_form,
    }

    return render_into_skin('organization_detail.html', data, request)
Exemple #12
0
 def save(self, *args, **kwargs):
     if not self.slug.strip():
         self.slug = slugify(self.title).replace("_", "-").strip()
     return super(StaticPage, self).save(*args, **kwargs)