Example #1
0
    def test_decorator(self):
        """register_view works as a decorator."""
        site = AdminSitePlus()

        @site.register_view(r'foo/bar')
        def foo_bar(request):
            return 'foo-bar'

        urls = site.get_urls()
        assert any(u.resolve('foo/bar') for u in urls)
Example #2
0
    def test_function(self):
        """register_view works as a function."""
        site = AdminSitePlus()

        def foo(request):
            return 'foo'
        site.register_view('foo', view=foo)

        urls = site.get_urls()
        assert any(u.resolve('foo') for u in urls)
Example #3
0
    def test_decorator(self):
        """register_view works as a decorator."""
        site = AdminSitePlus()

        @site.register_view(r'foo/bar')
        def foo_bar(request):
            return 'foo-bar'

        urls = site.get_urls()
        assert any(u.resolve('foo/bar') for u in urls)
Example #4
0
    def test_function(self):
        """register_view works as a function."""
        site = AdminSitePlus()

        def foo(request):
            return 'foo'
        site.register_view('foo', view=foo)

        urls = site.get_urls()
        assert any(u.resolve('foo') for u in urls)
Example #5
0
def monkeypatch():
    """All the monkeypatching we have to do to get things running"""
    global _has_patched
    if _has_patched:
        return

    # Import for side-effect: configures logging handlers
    from fjord.settings.log_settings import noop
    noop()

    # Monkey-patch admin site
    from django.contrib import admin
    from django.contrib.auth.decorators import login_required
    from session_csrf import anonymous_csrf
    from adminplus.sites import AdminSitePlus

    # Patch the admin
    admin.site = AdminSitePlus()
    admin.site.login = login_required(anonymous_csrf(admin.site.login))

    # Monkey-patch Django's csrf_protect decorator to use
    # session-based CSRF tokens
    import session_csrf
    session_csrf.monkeypatch()

    logging.debug('Note: monkeypatches executed in %s' % __file__)

    # Prevent it from being run again later
    _has_patched = True
Example #6
0
    def test_visibility(self):
        """Make sure visibility works."""
        site = AdminSitePlus()
        req_factory = RequestFactory()

        def always_visible(request):
            return 'i am here'
        site.register_view('always-visible', view=always_visible, visible=True)

        def always_hidden(request):
            return 'i am here, but not shown'
        site.register_view('always-hidden', view=always_visible, visible=False)

        cond = lambda req: req.user.pk == 1
        b = lambda s: s.encode('ascii') if hasattr(s, 'encode') else s

        @site.register_view(r'conditional-view', visible=cond)
        class ConditionallyVisible(View):
            def get(self, request):
                return 'hi there'

        urls = site.get_urls()
        assert any(u.resolve('always-visible') for u in urls)
        assert any(u.resolve('always-hidden') for u in urls)
        assert any(u.resolve('conditional-view') for u in urls)

        class MockUser(object):
            is_active = True
            is_staff = True

            def __init__(self, pk):
                self.pk = pk
                self.id = pk

        req_show = req_factory.get('/admin/')
        req_show.user = MockUser(1)
        result = site.index(req_show).render().content
        assert b('always-visible') in result
        assert b('always-hidden') not in result
        assert b('conditional-view') in result

        req_hide = req_factory.get('/admin/')
        req_hide.user = MockUser(2)
        result = site.index(req_hide).render().content
        assert b('always-visible') in result
        assert b('always-hidden') not in result
        assert b('conditional-view') not in result
Example #7
0
    def test_urlname(self):
        """Set URL pattern names correctly."""
        site = AdminSitePlus()

        @site.register_view("foo", urlname="foo")
        def foo(request):
            return "foo"

        @site.register_view("bar")
        def bar(request):
            return "bar"

        urls = site.get_urls()
        foo_urls = [u for u in urls if u.resolve("foo")]
        self.assertEqual(1, len(foo_urls))
        self.assertEqual("foo", foo_urls[0].name)

        bar_urls = [u for u in urls if u.resolve("bar")]
        self.assertEqual(1, len(bar_urls))
        assert bar_urls[0].name is None
Example #8
0
    def test_urlname(self):
        """Set URL pattern names correctly."""
        site = AdminSitePlus()

        @site.register_view('foo', urlname='foo')
        def foo(request):
            return 'foo'

        @site.register_view('bar')
        def bar(request):
            return 'bar'

        urls = site.get_urls()
        foo_urls = [u for u in urls if u.resolve('foo')]
        self.assertEqual(1, len(foo_urls))
        self.assertEqual('foo', foo_urls[0].name)

        bar_urls = [u for u in urls if u.resolve('bar')]
        self.assertEqual(1, len(bar_urls))
        assert bar_urls[0].name is None
Example #9
0
    def test_urlname(self):
        """Set URL pattern names correctly."""
        site = AdminSitePlus()

        @site.register_view('foo', urlname='foo')
        def foo(request):
            return 'foo'

        @site.register_view('bar')
        def bar(request):
            return 'bar'

        urls = site.get_urls()
        foo_urls = [u for u in urls if u.resolve('foo')]
        self.assertEqual(1, len(foo_urls))
        self.assertEqual('foo', foo_urls[0].name)

        bar_urls = [u for u in urls if u.resolve('bar')]
        self.assertEqual(1, len(bar_urls))
        assert bar_urls[0].name is None
Example #10
0
    def test_urlname(self):
        """Set URL pattern names correctly."""
        site = AdminSitePlus()

        @site.register_view('foo', urlname='foo')
        def foo(request):
            return 'foo'

        @site.register_view('bar')
        def bar(request):
            return 'bar'

        urls = site.get_urls()
        matches = lambda u: lambda p: p.resolve(u)
        foo_urls = filter(matches('foo'), urls)
        self.assertEqual(1, len(foo_urls))
        self.assertEqual('foo', foo_urls[0].name)

        bar_urls = filter(matches('bar'), urls)
        self.assertEqual(1, len(bar_urls))
        assert bar_urls[0].name is None
Example #11
0
def patch():
    global _has_been_patched

    if _has_been_patched:
        return

    fields.DateField.widget = DateWidget
    fields.TimeField.widget = TimeWidget

    # Workaround until https://code.djangoproject.com/ticket/16920 gets fixed.
    from django.contrib.admin import utils
    from django.contrib.admin.utils import NestedObjects
    from django.db import models

    def _collect(self, objs, source_attr=None, **kwargs):
        for obj in objs:
            if source_attr:
                # We just added a default of None below and that gets around
                # the problem.
                self.add_edge(getattr(obj, source_attr, None), obj)
            else:
                self.add_edge(None, obj)
        try:
            return super(NestedObjects, self).collect(objs,
                                                      source_attr=source_attr,
                                                      **kwargs)
        except models.ProtectedError as e:
            self.protected.update(e.protected_objects)

    utils.NestedObjects.collect = _collect

    # Monkey-patch admin site.
    from django.contrib import admin
    from adminplus.sites import AdminSitePlus

    # Patch the admin
    admin.site = AdminSitePlus()
    admin.sites.site = admin.site
    admin.site.site_header = "Kitsune Administration"
    admin.site.site_title = "Mozilla Support"

    # In testing contexts, patch django.shortcuts.render
    if TESTING:
        monkeypatch_render()

    _has_been_patched = True
Example #12
0
    def test_path(self):
        """Setting the path works correctly."""
        site = AdminSitePlus()

        def foo(request):
            return 'foo'
        site.register_view('foo', view=foo)
        site.register_view('bar/baz', view=foo)
        site.register_view('baz-qux', view=foo)

        urls = site.get_urls()

        foo_urls = [u for u in urls if u.resolve('foo')]
        self.assertEqual(1, len(foo_urls))
        bar_urls = [u for u in urls if u.resolve('bar/baz')]
        self.assertEqual(1, len(bar_urls))
        qux_urls = [u for u in urls if u.resolve('baz-qux')]
        self.assertEqual(1, len(qux_urls))
Example #13
0
    def test_path(self):
        """Setting the path works correctly."""
        site = AdminSitePlus()

        def foo(request):
            return 'foo'
        site.register_view('foo', view=foo)
        site.register_view('bar/baz', view=foo)
        site.register_view('baz-qux', view=foo)

        urls = site.get_urls()

        foo_urls = [u for u in urls if u.resolve('foo')]
        self.assertEqual(1, len(foo_urls))
        bar_urls = [u for u in urls if u.resolve('bar/baz')]
        self.assertEqual(1, len(bar_urls))
        qux_urls = [u for u in urls if u.resolve('baz-qux')]
        self.assertEqual(1, len(qux_urls))
Example #14
0
def patch():
    global _has_patched
    if _has_patched:
        return

    # Import for side-effect: configures logging handlers.
    from fjord.settings.log_settings import noop
    noop()

    # Monkey-patch admin site.
    from django.contrib import admin
    from django.contrib.auth.decorators import login_required
    from session_csrf import anonymous_csrf
    from adminplus.sites import AdminSitePlus

    # Patch the admin
    admin.site = AdminSitePlus()
    admin.site.login = login_required(anonymous_csrf(admin.site.login))

    # Monkey-patch django forms to avoid having to use Jinja2's |safe
    # everywhere.
    import jingo.monkey
    jingo.monkey.patch()

    # Monkey-patch Django's csrf_protect decorator to use
    # session-based CSRF tokens.
    import session_csrf
    session_csrf.monkeypatch()

    from jingo import load_helpers
    load_helpers()

    logging.debug("Note: monkey patches executed in %s" % __file__)

    # Prevent it from being run again later.
    _has_patched = True
Example #15
0
    def test_path(self):
        """Setting the path works correctly."""
        site = AdminSitePlus()

        def foo(request):
            return 'foo'
        site.register_view('foo', view=foo)
        site.register_view('bar/baz', view=foo)
        site.register_view('baz-qux', view=foo)

        urls = site.get_urls()

        matches = lambda u: lambda p: p.resolve(u)
        foo_urls = filter(matches('foo'), urls)
        self.assertEqual(1, len(foo_urls))
        bar_urls = filter(matches('bar/baz'), urls)
        self.assertEqual(1, len(bar_urls))
        qux_urls = filter(matches('baz-qux'), urls)
        self.assertEqual(1, len(qux_urls))
Example #16
0
"""The master router for the whole project
"""

from django.contrib import admin
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.conf import settings
from django.contrib import admin
from adminplus.sites import AdminSitePlus

# Admin setup
admin.site = AdminSitePlus()
admin.autodiscover()

urlpatterns = [
    url(r'^notflixadmin/', admin.site.urls),
    url(r'^cart/', include('cart.urls', namespace='cart')),
    url(r'^orders/', include('orders.urls', namespace='orders')),
    url(r'^users/', include('users.urls', namespace='users')),
    url(r'^stats/', include('stats.urls', namespace='stats')),
    url(r'^', include('movies.urls', namespace='movies')),
    #url(r'^users/', include('users.urls')),
]

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL,
                          document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL,
                          document_root=settings.MEDIA_ROOT)
Example #17
0
from django.contrib.auth.admin import GroupAdmin, UserAdmin
from django.contrib.auth.models import Group, User

from adminplus.sites import AdminSitePlus
from rest_framework.authtoken.admin import TokenAdmin
from rest_framework.authtoken.models import Token

site = AdminSitePlus()

site.site_header = 'SHIELD Server Admin'
site.site_title = 'SHIELD Server Admin'

# Register third-party apps.
site.register(Group, GroupAdmin)
site.register(User, UserAdmin)
site.register(Token, TokenAdmin)
Example #18
0
from django.contrib.auth.admin import GroupAdmin, UserAdmin
from django.contrib.auth.models import Group, User

from adminplus.sites import AdminSitePlus
from rest_framework.authtoken.admin import TokenAdmin
from rest_framework.authtoken.models import Token


site = AdminSitePlus()

site.site_header = 'SHIELD Server Admin'
site.site_title = 'SHIELD Server Admin'


# Register third-party apps.
site.register(Group, GroupAdmin)
site.register(User, UserAdmin)
site.register(Token, TokenAdmin)
Example #19
0
def patch():
    global _has_been_patched, URLWidget

    if _has_been_patched:
        return

    # Monkey patch preserves the old values, so we can pick up any changes
    # in CharField.widget_attrs and Field.widget_attrs
    # paulc filed a Django ticket for it, #14884
    field_widget_attrs = fields.Field.widget_attrs
    charfield_widget_attrs = fields.CharField.widget_attrs

    def required_field_attrs(self, widget):
        """This function is for use on the base Field class."""
        attrs = field_widget_attrs(self, widget)
        # required="required" isn't supported for groups of checkboxes.
        if (self.required and 'required' not in attrs and not widget.is_hidden
                and not isinstance(widget, widgets.CheckboxSelectMultiple)):
            attrs['required'] = 'required'
        return attrs

    def required_char_field_attrs(self, widget, *args, **kwargs):
        """This function is for use on the CharField class."""
        # We need to call super() here, since Django's CharField.widget_attrs
        # doesn't call its super and thus won't use the required_field_attrs
        # above.
        attrs = super(fields.CharField,
                      self).widget_attrs(widget, *args, **kwargs)
        original_attrs = charfield_widget_attrs(self, widget) or {}
        attrs.update(original_attrs)
        return attrs

    fields.Field.widget_attrs = required_field_attrs
    fields.CharField.widget_attrs = required_char_field_attrs
    fields.DateField.widget = DateWidget
    fields.TimeField.widget = TimeWidget
    fields.URLField.widget = URLWidget
    fields.EmailField.widget = EmailWidget

    # Workaround until https://code.djangoproject.com/ticket/16920 gets fixed.
    from django.contrib.admin import util
    from django.contrib.admin.util import NestedObjects
    from django.db import models

    def _collect(self, objs, source_attr=None, **kwargs):
        for obj in objs:
            if source_attr:
                # We just added a default of None below and that gets around
                # the problem.
                self.add_edge(getattr(obj, source_attr, None), obj)
            else:
                self.add_edge(None, obj)
        try:
            return super(NestedObjects, self).collect(objs,
                                                      source_attr=source_attr,
                                                      **kwargs)
        except models.ProtectedError as e:
            self.protected.update(e.protected_objects)

    util.NestedObjects.collect = _collect

    # Monkey-patch admin site.
    from django.contrib import admin
    from django.contrib.auth.decorators import login_required
    from adminplus.sites import AdminSitePlus

    # Patch the admin
    admin.site = AdminSitePlus()
    admin.site.login = login_required(admin.site.login)

    # Monkey patch django's csrf
    import session_csrf
    session_csrf.monkeypatch()

    # In testing contexts, patch django.shortcuts.render
    if 'TESTING' == 'TESTING':
        monkeypatch_render()

    _has_been_patched = True
Example #20
0
def patch():
    global _has_been_patched

    if _has_been_patched:
        return

    fields.DateField.widget = DateWidget
    fields.TimeField.widget = TimeWidget

    # Workaround until https://code.djangoproject.com/ticket/16920 gets fixed.
    from django.contrib.admin import utils
    from django.contrib.admin.utils import NestedObjects
    from django.db import models

    def _collect(self, objs, source_attr=None, **kwargs):
        for obj in objs:
            if source_attr:
                # We just added a default of None below and that gets around
                # the problem.
                self.add_edge(getattr(obj, source_attr, None), obj)
            else:
                self.add_edge(None, obj)
        try:
            return super(NestedObjects, self).collect(objs,
                                                      source_attr=source_attr,
                                                      **kwargs)
        except models.ProtectedError as e:
            self.protected.update(e.protected_objects)

    utils.NestedObjects.collect = _collect

    # Monkey-patch admin site.
    from django.contrib import admin
    from adminplus.sites import AdminSitePlus

    # Patch the admin
    admin.site = AdminSitePlus()
    admin.sites.site = admin.site
    admin.site.site_header = "Kitsune Administration"
    admin.site.site_title = "Mozilla Support"

    # In testing contexts, patch django.shortcuts.render
    if TESTING:
        monkeypatch_render()

    # Monkey patch ES
    def get_es(**overrides):
        """Monkey patch elasticutils get_es to add use_ssl and http_auth settings."""
        from django.conf import settings

        from elasticsearch import RequestsHttpConnection

        defaults = {
            "urls": settings.ES_URLS,
            "timeout": getattr(settings, "ES_TIMEOUT", 5),
            "use_ssl": getattr(settings, "ES_USE_SSL", False),
            "http_auth": getattr(settings, "ES_HTTP_AUTH", None),
            "verify_certs": getattr(settings, "ES_VERIFY_CERTS", True),
            "connection_class": RequestsHttpConnection,
        }

        defaults.update(overrides)
        return base_get_es(**defaults)

    elasticutils_django.get_es = get_es

    def S_get_es(self, default_builder=get_es):
        """Returns the elasticsearch Elasticsearch object to use.

        This uses the django get_es builder by default which takes
        into account settings in ``settings.py``.

        """
        return super(elasticutils_django.S,
                     self).get_es(default_builder=default_builder)

    elasticutils_django.S.get_es = S_get_es

    _has_been_patched = True
Example #21
0
from django.conf.urls import patterns, include, url
from django.contrib import admin
from adminplus.sites import AdminSitePlus

admin.site = AdminSitePlus() # for adminplus
admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'f_models.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),
    url(r'^admin_tools/', include('admin_tools.urls')),
    url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
    url(r'^admin/', include(admin.site.urls)),
)
Example #22
0
def patch():
    global _has_been_patched, URLWidget

    if _has_been_patched:
        return

    # Monkey patch preserves the old values, so we can pick up any changes
    # in CharField.widget_attrs and Field.widget_attrs
    # paulc filed a Django ticket for it, #14884
    field_widget_attrs = fields.Field.widget_attrs
    charfield_widget_attrs = fields.CharField.widget_attrs

    def required_field_attrs(self, widget):
        """This function is for use on the base Field class."""
        attrs = field_widget_attrs(self, widget)
        # required="required" isn't supported for groups of checkboxes.
        if (self.required and 'required' not in attrs and not widget.is_hidden
                and not isinstance(widget, widgets.CheckboxSelectMultiple)):
            attrs['required'] = 'required'
        return attrs

    def required_char_field_attrs(self, widget, *args, **kwargs):
        """This function is for use on the CharField class."""
        # We need to call super() here, since Django's CharField.widget_attrs
        # doesn't call its super and thus won't use the required_field_attrs
        # above.
        attrs = super(fields.CharField,
                      self).widget_attrs(widget, *args, **kwargs)
        original_attrs = charfield_widget_attrs(self, widget) or {}
        attrs.update(original_attrs)
        return attrs

    fields.Field.widget_attrs = required_field_attrs
    fields.CharField.widget_attrs = required_char_field_attrs
    fields.DateField.widget = DateWidget
    fields.TimeField.widget = TimeWidget
    fields.URLField.widget = URLWidget
    fields.EmailField.widget = EmailWidget

    # Workaround until https://code.djangoproject.com/ticket/16920 gets fixed.
    from django.contrib.admin import util
    from django.contrib.admin.util import NestedObjects
    from django.db import models

    def _collect(self, objs, source_attr=None, **kwargs):
        for obj in objs:
            if source_attr:
                # We just added a default of None below and that gets around
                # the problem.
                self.add_edge(getattr(obj, source_attr, None), obj)
            else:
                self.add_edge(None, obj)
        try:
            return super(NestedObjects, self).collect(objs,
                                                      source_attr=source_attr,
                                                      **kwargs)
        except models.ProtectedError as e:
            self.protected.update(e.protected_objects)

    util.NestedObjects.collect = _collect

    # Monkey-patch admin site.
    from django.contrib import admin
    from adminplus.sites import AdminSitePlus

    # Patch the admin
    admin.site = AdminSitePlus()
    admin.site.site_header = 'Kitsune Administration'
    admin.site.site_title = 'Mozilla Support'

    # Monkey patch django's csrf
    import session_csrf
    session_csrf.monkeypatch()

    # In testing contexts, patch django.shortcuts.render
    if 'TESTING' == 'TESTING':
        monkeypatch_render()

    # Monkey patch ES
    def get_es(**overrides):
        """Monkey patch elasticutils get_es to add use_ssl and http_auth settings."""
        from django.conf import settings

        defaults = {
            'urls': settings.ES_URLS,
            'timeout': getattr(settings, 'ES_TIMEOUT', 5),
            'use_ssl': getattr(settings, 'ES_USE_SSL', False),
            'http_auth': getattr(settings, 'ES_HTTP_AUTH', None),
            'verify_certs': getattr(settings, 'ES_VERIFY_CERTS', True),
        }

        defaults.update(overrides)
        return base_get_es(**defaults)

    elasticutils_django.get_es = get_es

    def S_get_es(self, default_builder=get_es):
        """Returns the elasticsearch Elasticsearch object to use.

        This uses the django get_es builder by default which takes
        into account settings in ``settings.py``.

        """
        return super(elasticutils_django.S,
                     self).get_es(default_builder=default_builder)

    elasticutils_django.S.get_es = S_get_es

    _has_been_patched = True
Example #23
0
from django.contrib import admin, messages
from invitation.models import Invitation, Person, str_is_english
from invitation.export import export_to_hall_excel, EXPORT_HALL_NAME
from invitation.export import export_all_info, EXPORT_ALL_INFO_NAME
from invitation.export import export_rides, EXPORT_RIDES_NAME
from django.shortcuts import render, render_to_response
from django.http import HttpResponseRedirect, HttpResponse
from adminplus.sites import AdminSitePlus
from invitation.statistics import Statistics
from invitation.email import email_invite
from django.contrib.admin import helpers
from django.template import RequestContext
from django.utils.translation import ugettext_lazy as _

site = AdminSitePlus()
site.site_header = "Gavi and Ariela's Admin page!"

email_templates = ["initial"]


def export_to_app_excel(InvitationAdmin, request, queryset):
    export_to_hall_excel(queryset)
    output = open(EXPORT_HALL_NAME, "rb")
    output.seek(0)
    response = HttpResponse(
        output.read(),
        content_type=
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
    response[
        'Content-Disposition'] = "attachment; filename=Info_for_hall_app.xlsx"
    return response