Example #1
0
    def index(self, request, extra_context=None):
        """
        Displays the main Newman index page, without installed apps.
        """
        data = {'sites': []}
        try:
            data['sites'] = get_user_config(request.user, CATEGORY_FILTER)
        except KeyError:
            data['sites'] = []

        site_filter_form = SiteFilterForm(data=data, user=request.user)
        cts = []
        last_filters = {}
        for model, model_admin in self._registry.items():
            if has_model_list_permission(request.user, model):
                ct = ContentType.objects.get_for_model(model)
                cts.append(ct)
                # Load saved filter configurations for changelists
                key = 'filter__%s__%s' % (ct.app_label, ct.model)
                last_filter = AdminSetting.objects.filter(var=key, user=request.user)
                if last_filter:
                    last_filters[key] = '?%s' % json_decode(last_filter[0].value)

        context = {
            'title': _('Site administration'),
            'site_filter_form': site_filter_form,
            'searchable_content_types': cts,
            'last_filters': last_filters
        }
        context.update(extra_context or {})
        return render_to_response(self.index_template or 'admin/index.html', context,
            context_instance=template.RequestContext(request)
        )
Example #2
0
    def changelist_view(self, request, extra_context=None):
        self.register_newman_variables(request)

        context = super(NewmanModelAdmin, self).get_changelist_context(request)
        if type(context) != dict:
            return context

        if context['media']:
            raw_media = self.prepare_media(context['media'])
            context['media'] = raw_media

        # save per user filtered content type.
        req_path = request.get_full_path()
        ct = ContentType.objects.get_for_model(self.model)
        # persistent filter for non-popupped changelists only
        key = 'filter__%s__%s' % (ct.app_label, ct.model)
        if req_path.find('pop') < 0:
            if req_path.find('?') > 0:
                url_args = req_path.split('?', 1)[1]
                utils.set_user_config_db(request.user, key, url_args)
            else:
                user_filter = utils.get_user_config(request.user, key)
                if user_filter:
                    redirect_to = '%s?%s' % (request.path, user_filter)
                    return utils.JsonResponseRedirect(redirect_to)

        context['is_filtered'] = context['cl'].is_filtered()
        context['is_user_category_filtered'] = utils.is_user_category_filtered( self.queryset(request) )
        context.update(extra_context or {})
        return render_to_response(self.change_list_template, context, context_instance=template.RequestContext(request))
Example #3
0
    def newman_index(self, request, extra_context=None):
        def translate_and_upper(text):
            return ugettext(text).upper()

        """
        Displays the main Newman index page, without installed apps.
        """
        data = {'sites': []}
        try:
            data['sites'] = get_user_config(request.user,
                                            newman_settings.CATEGORY_FILTER)
        except KeyError:
            data['sites'] = []

        publishable_lookup_fields = {
            'day': 'publish_from__day',
            'month': 'publish_from__month',
            'year': 'publish_from__year'
        }
        site_filter_form = SiteFilterForm(data=data, user=request.user)
        if site_filter_form.sites_count == 1:
            site_filter_form = None
        cts = []
        last_filters = {}
        for model, model_admin in self._registry.items():
            if has_model_list_permission(request.user,
                                         model) and model_admin.search_fields:
                ct = ContentType.objects.get_for_model(model)
                cts.append(ct)
                # Load saved filter configurations for changelists
                key = 'filter__%s__%s' % (ct.app_label, ct.model)
                last_filter = AdminSetting.objects.filter(var=key,
                                                          user=request.user)
                if last_filter:
                    last_filters[key] = '?%s' % json_decode(
                        last_filter[0].value)

        future_qs = Placement.objects.select_related().filter(
            publish_from__gt=datetime.datetime.now()).order_by(
                'publish_from', 'category__tree_path')
        future_qs_perm = permission_filtered_model_qs(future_qs, request.user)
        future_placements = user_category_filter(future_qs_perm, request.user)

        cts.sort(lambda a, b: cz_compare(translate_and_upper(a.name),
                                         translate_and_upper(b.name)))
        context = {
            'title': _('Site administration'),
            'site_filter_form': site_filter_form,
            'searchable_content_types': cts,
            'last_filters': last_filters,
            'future_placements': future_placements,
            'publishable_lookup_fields': publishable_lookup_fields,
            'show_calendar': has_model_list_permission(request.user,
                                                       Publishable),
        }
        context.update(extra_context or {})
        return render_to_response(
            'newman/newman-index.html',
            context,
            context_instance=template.RequestContext(request))
Example #4
0
    def login(self, request):
        """
        Displays the login form for the given HttpRequest.
        """
        from django.contrib.auth.models import User

        ERROR_MESSAGE = _("Please enter a correct username and password. Note that both fields are case-sensitive.")
        LOGIN_FORM_KEY = 'this_is_the_login_form'

        # If this isn't already the login page, display it.
        if not request.POST.has_key(LOGIN_FORM_KEY):
            if request.POST:
                message = _("Please log in again, because your session has expired.")
            else:
                message = ""
            return self.display_login_form(request, message)

        # Check that the user accepts cookies.
        if not request.session.test_cookie_worked():
            message = _("Looks like your browser isn't configured to accept cookies. Please enable cookies, reload this page, and try again.")
            return self.display_login_form(request, message)
        else:
            request.session.delete_test_cookie()

        # Check the password.
        username = request.POST.get('username', None)
        password = request.POST.get('password', None)
        user = authenticate(username=username, password=password)
        if user is None:
            message = ERROR_MESSAGE
            if u'@' in username:
                # Mistakenly entered e-mail address instead of username? Look it up.
                try:
                    user = User.objects.get(email=username)
                except (User.DoesNotExist, User.MultipleObjectsReturned):
                    message = _("Usernames cannot contain the '@' character.")
                else:
                    if user.check_password(password):
                        message = _("Your e-mail address is not your username."
                                    " Try '%s' instead.") % user.username
                    else:
                        message = _("Usernames cannot contain the '@' character.")
            return self.display_login_form(request, message)

        # The user data is correct; log in the user in and continue.
        else:
            if user.is_active and user.is_staff:
                login(request, user)
                # user has no applicable categories, probably his role is undefined
                if not applicable_categories(user):
                    return self.norole(request, user)
                # load all user's specific settings into session
                for c in AdminSetting.objects.filter(user=user):
                    uc = get_user_config(user, c.var)
                    set_user_config_session(request.session, c.var, uc)
                return HttpResponseRedirect(request.get_full_path())
            else:
                return self.display_login_form(request, ERROR_MESSAGE)
Example #5
0
File: sites.py Project: joskid/ella
    def newman_index(self, request, extra_context=None):
        def translate_and_upper(text):
            return ugettext(text).upper()

        """
        Displays the main Newman index page, without installed apps.
        """
        data = {'sites': []}
        try:
            data['sites'] = get_user_config(request.user, newman_settings.CATEGORY_FILTER)
        except KeyError:
            data['sites'] = []

        publishable_lookup_fields = {
            'day': 'publish_from__day',
            'month': 'publish_from__month',
            'year': 'publish_from__year'
        }
        site_filter_form = SiteFilterForm(data=data, user=request.user)
        if site_filter_form.sites_count == 1:
            site_filter_form = None
        cts = []
        last_filters = {}
        for model, model_admin in self._registry.items():
            if has_model_list_permission(request.user, model) and model_admin.search_fields:
                ct = ContentType.objects.get_for_model(model)
                cts.append(ct)
                # Load saved filter configurations for changelists
                key = 'filter__%s__%s' % (ct.app_label, ct.model)
                last_filter = AdminSetting.objects.filter(var=key, user=request.user)
                if last_filter:
                    last_filters[key] = '?%s' % json_decode(last_filter[0].value)

        future_qs = Placement.objects.select_related().filter(publish_from__gt=datetime.datetime.now()).order_by('publish_from', 'category__tree_path')
        future_qs_perm = permission_filtered_model_qs(future_qs, request.user)
        future_placements = user_category_filter(future_qs_perm, request.user)

        cts.sort( lambda a, b: cz_compare(translate_and_upper(a.name), translate_and_upper(b.name)) )
        context = {
            'title': _('Site administration'),
            'site_filter_form': site_filter_form,
            'searchable_content_types': cts,
            'last_filters': last_filters,
            'future_placements': future_placements,
            'publishable_lookup_fields': publishable_lookup_fields,
            'show_calendar': has_model_list_permission(request.user, Publishable),
        }
        context.update(extra_context or {})
        return render_to_response('newman/newman-index.html', context,
            context_instance=template.RequestContext(request)
        )
Example #6
0
def site_field_filter(fspec):
    category_ids = get_user_config(fspec.user, CATEGORY_FILTER)
    if not category_ids:
        if not fspec.user.is_superuser:
            category_ids = m.DenormalizedCategoryUserRole.objects.root_categories_by_user(fspec.user)
        else:
            category_ids = Category.objects.filter(tree_parent=None)
    qs = Category.objects.filter(pk__in=category_ids)
    sites = map(lambda c: c.site, qs)
    for site in sites:
        #category__site__id__exact=1
        lookup_var = '%s__%s__exact' % (fspec.f.name, fspec.f.rel.get_related_field().name)
        link = ( site, {lookup_var: site.pk})
        fspec.links.append(link)
    return True
Example #7
0
File: sites.py Project: joskid/ella
    def filter_by_main_categories(self, request, extra_context=None):
        data = {'sites': []}
        try:
            data['sites'] = get_user_config(request.user, newman_settings.CATEGORY_FILTER)
        except KeyError:
            data['sites'] = []
        site_filter_form = SiteFilterForm(data=data, user=request.user)

        context = {'site_filter_form': site_filter_form}
        if extra_context:
            context.update(extra_context)
        return render_to_response(
            'newman/main-categories-filter.html',
            context,
            context_instance=template.RequestContext(request)
        )
Example #8
0
    def filter_by_main_categories(self, request, extra_context=None):
        data = {'sites': []}
        try:
            data['sites'] = get_user_config(request.user,
                                            newman_settings.CATEGORY_FILTER)
        except KeyError:
            data['sites'] = []
        site_filter_form = SiteFilterForm(data=data, user=request.user)

        context = {'site_filter_form': site_filter_form}
        if extra_context:
            context.update(extra_context)
        return render_to_response(
            'newman/main-categories-filter.html',
            context,
            context_instance=template.RequestContext(request))
Example #9
0
File: options.py Project: whit/ella
    def changelist_view(self, request, extra_context=None):
        self.register_newman_variables(request)

        # save per user filtered content type.
        is_popup = False
        req_path = request.get_full_path()
        ct = ContentType.objects.get_for_model(self.model)
        # persistent filter for non-popupped changelists only
        key = 'filter__%s__%s' % (ct.app_label, ct.model)
        if req_path.find(
                'pop'
        ) >= 0:  # if popup is displayed, remove pop string from request path
            is_popup = True
            req_path = re.sub(r'(.*)(pop=&|&pop=|pop=|pop&|&pop|pop)(.*)',
                              r'\1\3', req_path)
        if req_path.endswith('?') and is_popup:
            req_path = ''  # if popup with no active filters is displayed, do not save empty filter settings
        if req_path.find('?') > 0:
            url_args = req_path.split('?', 1)[1]
            utils.set_user_config_db(request.user, key, url_args)
            log.debug('SAVING FILTERS %s' % url_args)
        else:
            user_filter = utils.get_user_config(request.user, key)
            if user_filter:
                if is_popup:
                    user_filter = 'pop&%s' % user_filter
                redirect_to = '%s?%s' % (request.path, user_filter)
                if not redirect_to.endswith('?q='):
                    log.debug('REDIRECTING TO %s' % redirect_to)
                    return utils.JsonResponseRedirect(redirect_to)

        context = super(NewmanModelAdmin, self).get_changelist_context(request)
        if type(context) != dict:
            return context

        if context['media']:
            raw_media = self.prepare_media(context['media'])
            context['media'] = raw_media

        context['is_filtered'] = context['cl'].is_filtered()
        context['is_user_category_filtered'] = utils.is_user_category_filtered(
            self.queryset(request))
        context.update(extra_context or {})
        return render_to_response(
            self.change_list_template,
            context,
            context_instance=template.RequestContext(request))
Example #10
0
    def changelist_view(self, request, extra_context=None):
        self.register_newman_variables(request)

        # save per user filtered content type.
        is_popup = False
        req_path = request.get_full_path()
        ct = ContentType.objects.get_for_model(self.model)
        # persistent filter for non-popupped changelists only
        key = 'filter__%s__%s' % (ct.app_label, ct.model)
        if req_path.find('pop') >= 0: # if popup is displayed, remove pop string from request path
            is_popup = True
            req_path = re.sub(r'(.*)(pop=&|&pop=|pop=|pop&|&pop|pop)(.*)', r'\1\3', req_path)
        if req_path.endswith('?') and is_popup:
            req_path = '' # if popup with no active filters is displayed, do not save empty filter settings
        if req_path.find('?') > 0:
            url_args = req_path.split('?', 1)[1]
            utils.set_user_config_db(request.user, key, url_args)
            log.debug('SAVING FILTERS %s' % url_args)
        else:
            user_filter = utils.get_user_config(request.user, key)
            if user_filter:
                if is_popup:
                    user_filter = 'pop&%s' % user_filter
                redirect_to = '%s?%s' % (request.path, user_filter)
                if not redirect_to.endswith('?q='):
                    log.debug('REDIRECTING TO %s' % redirect_to)
                    return utils.JsonResponseRedirect(redirect_to)

        context = super(NewmanModelAdmin, self).get_changelist_context(request)
        if type(context) != dict:
            return context

        if context['media']:
            raw_media = self.prepare_media(context['media'])
            context['media'] = raw_media

        context['is_filtered'] = context['cl'].is_filtered()
        context['is_user_category_filtered'] = utils.is_user_category_filtered( self.queryset(request) )
        context.update(extra_context or {})
        return render_to_response(self.change_list_template, context, context_instance=template.RequestContext(request))
Example #11
0
    def login(self, request):
        """
        Displays the login form for the given HttpRequest.
        """
        from django.contrib.auth.models import User

        ERROR_MESSAGE = _(
            "Please enter a correct username and password. Note that both fields are case-sensitive."
        )
        LOGIN_FORM_KEY = 'this_is_the_login_form'

        # If this isn't already the login page, display it.
        if not request.POST.has_key(LOGIN_FORM_KEY):
            if request.POST:
                message = _(
                    "Please log in again, because your session has expired.")
            else:
                message = ""
            return self.display_login_form(request, message)
            #return self.login(request)

        # Check that the user accepts cookies.
        if not request.session.test_cookie_worked():
            message = _(
                "Looks like your browser isn't configured to accept cookies. Please enable cookies, reload this page, and try again."
            )
            return self.display_login_form(request, message)
        else:
            request.session.delete_test_cookie()

        # Check the password.
        username = request.POST.get('username', None)
        password = request.POST.get('password', None)
        user = authenticate(username=username, password=password)
        if user is None:
            message = ERROR_MESSAGE
            if u'@' in username:
                # Mistakenly entered e-mail address instead of username? Look it up.
                try:
                    user = User.objects.get(email=username)
                except (User.DoesNotExist, User.MultipleObjectsReturned):
                    message = _("Usernames cannot contain the '@' character.")
                else:
                    if user.check_password(password):
                        message = _("Your e-mail address is not your username."
                                    " Try '%s' instead.") % user.username
                    else:
                        message = _(
                            "Usernames cannot contain the '@' character.")
            return self.display_login_form(request, message)

        # The user data is correct; log in the user in and continue.
        else:
            if user.is_active and user.is_staff:
                login(request, user)
                # user has no applicable categories, probably his role is undefined
                if not applicable_categories(user) and not user.is_superuser:
                    return self.norole(request, user)

                next_path = request.get_full_path()

                # load all user's specific settings into session
                for c in AdminSetting.objects.filter(user=user).values('var'):
                    uc = get_user_config(user, c['var'])
                    set_user_config_session(request.session, c['var'], uc)

                if request.POST.get('next'):
                    next_path += request.POST.get('next')
                return HttpResponseRedirect(next_path)
            else:
                return self.display_login_form(request, ERROR_MESSAGE)