Ejemplo n.º 1
0
 def monkeypatch_user(sender, **kwargs):
     profile_model = get_profile_model()
     exclude_names = set(field.name for field in User._meta.fields)
     exclude_names.add('user')
     if include is not None:
         if exclude is not None:
             raise ValueError('Cannot pass both "include" and "exclude"')
         include_names = set(include) - exclude_names
         iterfields = (field for field in profile_model._meta.fields
                       if field.name in include_names)
     else:
         if exclude:
             exclude_names.update(exclude)
         iterfields = (field for field in profile_model._meta.fields
                       if field.name not in exclude_names)
     for field in iterfields:
         name = field.name    
         setattr_if_unset(User, name, _make_profile_property(name))
         if field.choices:
             setattr_if_unset(User, 'get_%s_display' % name,
                              curry(User._get_FIELD_display, field=field))
         if isinstance(field, (DateField, DateTimeField)) and not field.null:
             setattr_if_unset(User, 'get_next_by_%s' % name,
                              curry(_get_next_or_previous_by_profile_FIELD,
                                    field=field, is_next=True))
             setattr_if_unset(User, 'get_previous_by_%s' % name,
                              curry(_get_next_or_previous_by_profile_FIELD,
                                    field=field, is_next=False))
     post_save.connect(_save_profile_listener, sender=User)
     connection_created.disconnect(monkeypatch_user)
Ejemplo n.º 2
0
 def contribute_to_class(self, cls, name):
     super(DateField,self).contribute_to_class(cls, name)
     if not self.null:
         setattr(cls, 'get_next_by_%s' % self.name,
             curry(cls._get_next_or_previous_by_FIELD, field=self, is_next=True))
         setattr(cls, 'get_previous_by_%s' % self.name,
             curry(cls._get_next_or_previous_by_FIELD, field=self, is_next=False))
Ejemplo n.º 3
0
 def process_request(self, request):
     if getattr(settings, 'DISABLE_AUDIT_LOG', False):
         return
     update_pre_save_info = curry(self._update_pre_save_info, request)
     update_post_save_info = curry(self._update_post_save_info, request)
     signals.pre_save.connect(update_pre_save_info, dispatch_uid=(self.__class__, request,), weak = False)
     signals.post_save.connect(update_post_save_info, dispatch_uid=(self.__class__, request,), weak = False)
Ejemplo n.º 4
0
    def contribute_to_class(self, cls, name):
        super(StateField, self).contribute_to_class(cls, name)

        # Set choice options (for combo box)
        self._choices = self._machine.get_state_choices()
        self.default = self._machine.initial_state

        # do we need logging?
        if self._machine.log_transitions:
            from states2.log import _create_state_log_model
            log_model = _create_state_log_model(cls, name, self._machine)
        else:
            log_model = None

        setattr(cls, '_%s_log_model' % name, log_model)

        # adding extra methods
        setattr(cls, 'get_%s_transitions' % name,
            curry(get_STATE_transitions, field=name))
        setattr(cls, 'get_public_%s_transitions' % name,
            curry(get_public_STATE_transitions, field=name))
        setattr(cls, 'get_%s_info' % name,
            curry(get_STATE_info, field=name, machine=self._machine))
        setattr(cls, 'get_%s_machine' % name,
            curry(get_STATE_machine, field=name, machine=self._machine))

        models.signals.class_prepared.connect(self.finalize, sender=cls)
Ejemplo n.º 5
0
    def contribute_to_class(self, cls, name):
        ensure_class_has_cached_field_methods(cls)
        self.name = name
        setattr(cls,
                'recalculate_{}'.format(self.name),
                curry(cls._recalculate_FIELD, field=self))
        setattr(cls,
                self.name,
                property(curry(cls._get_FIELD, field=self), curry(cls._set_FIELD, field=self)))

        proper_field = (set(type(self).__bases__) - set((CachedFieldMixin,))).pop()  # :MC: ew.
        proper_field = proper_field(*self.init_args_for_field, **self.init_kwargs_for_field)
        setattr(cls, self.cached_field_name, proper_field)
        proper_field.contribute_to_class(cls, self.cached_field_name)

        flag_field = models.BooleanField(
            default=True, db_index=self.db_index_on_recalculation_needed_field)
        setattr(cls, self.recalculation_needed_field_name, flag_field)
        flag_field.contribute_to_class(cls, self.recalculation_needed_field_name)

        if self.temporal_triggers:
            setattr(cls,
                    'expire_{}_after'.format(self.name),
                    curry(cls._expire_FIELD_after, field=self))
            expire_field = models.DateTimeField(
                null=True, db_index=self.db_index_on_temporal_trigger_field)
            setattr(cls, self.expiration_field_name, expire_field)
            expire_field.contribute_to_class(cls, self.expiration_field_name)

        setattr(cls, 'flag_{}_as_stale'.format(self.name), curry(cls._flag_FIELD_as_stale, field=self))
Ejemplo n.º 6
0
    def _prepare(cls):
        """
        Creates some methods once self._meta has been populated.
        """
        opts = cls._meta
        opts._prepare(cls)

        if opts.order_with_respect_to:
            cls.get_next_in_order = curry(cls._get_next_or_previous_in_order, is_next=True)
            cls.get_previous_in_order = curry(cls._get_next_or_previous_in_order, is_next=False)

            # defer creating accessors on the foreign class until we are
            # certain it has been created
            def make_foreign_order_accessors(field, model, cls):
                setattr(field.rel.to, "get_%s_order" % cls.__name__.lower(), curry(method_get_order, cls))
                setattr(field.rel.to, "set_%s_order" % cls.__name__.lower(), curry(method_set_order, cls))

            add_lazy_relation(
                cls, opts.order_with_respect_to, opts.order_with_respect_to.rel.to, make_foreign_order_accessors
            )

        # Give the class a docstring -- its definition.
        if cls.__doc__ is None:
            cls.__doc__ = "%s(%s)" % (cls.__name__, ", ".join(f.attname for f in opts.fields))

        if hasattr(cls, "get_absolute_url"):
            cls.get_absolute_url = update_wrapper(
                curry(get_absolute_url, opts, cls.get_absolute_url), cls.get_absolute_url
            )

        signals.class_prepared.send(sender=cls)
Ejemplo n.º 7
0
    def add_m2m_table(self, app_label, proj_sig):
        app_sig = proj_sig[app_label]
        model_sig = app_sig[self.model_name]

        model = MockModel(proj_sig, app_label, self.model_name, model_sig)

        field = create_field(proj_sig, self.field_name, self.field_type,
                             self.field_attrs, model)

        related_app_label, related_model_name = \
            self.field_attrs['related_model'].split('.')
        related_sig = proj_sig[related_app_label][related_model_name]
        related_model = MockModel(proj_sig, related_app_label,
                                  related_model_name, related_sig)
        related = MockRelated(related_model, model, field)

        if hasattr(field, '_get_m2m_column_name'):
            # Django < 1.2
            field.m2m_column_name = curry(field._get_m2m_column_name, related)
            field.m2m_reverse_name = curry(field._get_m2m_reverse_name, related)
        else:
            # Django >= 1.2
            field.m2m_column_name = curry(field._get_m2m_attr,
                                          related, 'column')
            field.m2m_reverse_name = curry(field._get_m2m_reverse_attr,
                                           related, 'column')

        sql_statements = self.evolver(model).add_m2m_table(model, field)

        return sql_statements
Ejemplo n.º 8
0
def wiki_links(text, group=None):
    """Replaces CamelCase words to wiki-links."""
    from BeautifulSoup import BeautifulSoup

    autoescape = False
    safe_input = isinstance(text, SafeData)
    conditional_escape(text)
    soup = BeautifulSoup(text)

    for url in soup.findAll(text=wikiword_link):
        if url.parent.name == 'a':
            continue
        new_str = wikiword_link.sub(curry(_re_callback, inside=False, group=group), url)
        url.replaceWith(BeautifulSoup(new_str))

    soup = BeautifulSoup(str(soup))  # Fixed for bug in some versions of BS
    for a in soup.findAll('a'):
        url = a.get('href')
        if not url:
            continue
        new_str = wikiword_link_href.sub(curry(_re_callback, inside=True, group=group), url)
        if new_str != url:
            a['href'] = new_str

    result = force_unicode(soup)
    if safe_input:
        result = mark_safe(result)
    elif autoescape:
        result = escape(result)
    return result
Ejemplo n.º 9
0
    def contribute_to_class(self, cls, name):
        self.name = self.attname = name
        cls._meta.add_virtual_field(self)

        self.inherit_flag_name = INHERIT_FLAG_NAME % name
        self.value_field_name = VALUE_FIELD_NAME % name

        if not self.inherit_only:
            flag_field = BooleanField(default=True)
            flag_field.creation_counter = self.creation_counter

            # Adjust the creation_counter
            # cls.add_to_class(self.inherit_flag_name, flag_field)
            flag_field.contribute_to_class(cls, self.inherit_flag_name)

            signals.class_prepared.connect(
                curry(self.add_value_field, name=name),
                sender=cls,
                weak=False
            )

        setattr(cls, name, self)
        display_name = 'get_%s_display' % name
        setattr(cls, display_name, curry(self.get_field_display, name=name))
        getattr(cls, display_name).__dict__['short_description'] = name.replace('_', ' ')

        if not hasattr(cls, 'FIELD_INHERITANCE_MAP'): #TODO: test
            cls.FIELD_INHERITANCE_MAP = {}

        cls.FIELD_INHERITANCE_MAP[name] = (self.parent_object_field_name, self.inherited_field_name_in_parent or name)
        signals.class_prepared.connect(self.patch_manager, sender=cls)
Ejemplo n.º 10
0
    def process_request(self, request):
        if request.method not in ('GET', 'HEAD', 'OPTIONS', 'TRACE'):
            if hasattr(request, 'user') and request.user.is_authenticated():
                user = request.user
            else:
                user = None

            session = request.session.session_key
            self.ip_address = request.META.get('REMOTE_ADDR', None)
            update_post_save_info = curry(
                self._update_post_save_info,
                user,
                session,
            )
            update_post_delete_info = curry(
                self._update_post_delete_info,
                user,
                session,
            )

            signals.post_save.connect(
                update_post_save_info,
                dispatch_uid=(self.__class__, request,),
                weak=False
            )
            signals.post_delete.connect(
                update_post_delete_info,
                dispatch_uid=(self.__class__, request,),
                weak=False
            )
Ejemplo n.º 11
0
    def add_m2m_table(self, app_label, proj_sig, database):
        app_sig = proj_sig[app_label]
        model_sig = app_sig[self.model_name]

        model = MockModel(proj_sig, app_label, self.model_name, model_sig)

        field = create_field(proj_sig, self.field_name, self.field_type, self.field_attrs, model)

        related_app_label, related_model_name = self.field_attrs["related_model"].split(".")
        related_sig = proj_sig[related_app_label][related_model_name]
        related_model = MockModel(proj_sig, related_app_label, related_model_name, related_sig)
        related = MockRelated(related_model, model, field)

        if hasattr(field, "_get_m2m_column_name"):
            # Django < 1.2
            field.m2m_column_name = curry(field._get_m2m_column_name, related)
            field.m2m_reverse_name = curry(field._get_m2m_reverse_name, related)
        else:
            # Django >= 1.2
            field.m2m_column_name = curry(field._get_m2m_attr, related, "column")
            field.m2m_reverse_name = curry(field._get_m2m_reverse_attr, related, "column")

        evolver = self.evolver(model, database)
        sql_statements = evolver.add_m2m_table(model, field)

        return sql_statements
Ejemplo n.º 12
0
    def add_m2m_table(self, mutator, model):
        field = create_field(mutator.proj_sig, self.field_name,
                             self.field_type, self.field_attrs, model)

        related_app_label, related_model_name = \
            self.field_attrs['related_model'].split('.')
        related_sig = mutator.proj_sig[related_app_label][related_model_name]
        related_model = MockModel(mutator.proj_sig, related_app_label,
                                  related_model_name, related_sig,
                                  mutator.database)
        related = MockRelated(related_model, model, field)

        if hasattr(field, '_get_m2m_column_name'):
            # Django < 1.2
            field.m2m_column_name = \
                curry(field._get_m2m_column_name, related)
            field.m2m_reverse_name = \
                curry(field._get_m2m_reverse_name, related)
        else:
            # Django >= 1.2
            field.m2m_column_name = curry(field._get_m2m_attr,
                                          related, 'column')
            field.m2m_reverse_name = curry(field._get_m2m_reverse_attr,
                                           related, 'column')

        mutator.add_sql(self, mutator.evolver.add_m2m_table(model, field))
Ejemplo n.º 13
0
def add_camara_text_utils_to_class(cls):
    """
    Adds camara values text representation utils to model fields whose
    `choices` is ``CAMARA_CHOICES``

    Added instance methods:

     - get_<fname>_slug(): slug text representation for camara value.
     - get_<fname>_display_long(): long text representation for camara value.
     - get_<fname>_display_short(): short text representation for camara value.
          This is the same value exposed by get_<fname>_display by default.
    """

    def _get_display(obj, attr, displays, default=u""):
        return displays.get(getattr(obj, attr), default)

    for f in cls._meta.fields:
        if f.choices is CAMARA_CHOICES:
            cls.add_to_class("get_%s_slug" % f.name, curry(_get_display, attr=f.name, displays=CAMARA_SLUGS))

            cls.add_to_class(
                "get_%s_display_long" % f.name, curry(_get_display, attr=f.name, displays=CAMARA_DISPLAYS_LONG)
            )

            # this is the same as self.get_<fname>_display. Added just for completeness
            cls.add_to_class(
                "get_%s_display_short" % f.name, curry(_get_display, attr=f.name, displays=CAMARA_DISPLAYS_SHORT)
            )
Ejemplo n.º 14
0
def edit(request, id):
    provider = request.user.service_provider
    employee = get_object_or_404(Employee, employer=request.user.service_provider, id=id)
    hours = EmployeeWorkingHours.objects.filter(employee=employee)
    services = Service.objects.filter(service_provider=provider, employees__in=[employee.id])
    if request.method == 'POST':
        if request.POST.get('action') == 'delete':
            EmployeeWorkingHours.objects.get(id=request.POST.get('workinghours')).delete()
            return HttpResponseRedirect('/myemployees/edit/' + id)
        form = EmployeeForm(request.POST, request.FILES, instance=employee)
        qs = EmployeeWorkingHours.objects.filter(employee=employee)
        EmployeeWorkingHoursFormSet.form = staticmethod(curry(EmployeeWorkingHoursForm, employee=employee))
        forms = EmployeeWorkingHoursFormSet(request.POST)
        form_s = EmployeeServicesForm(request.POST, service_provider=provider, employee=employee, data=services)
        form_valid = form.is_valid()
        form_s_valid = form_s.is_valid()
        forms_valid = True
        for f in forms:
            if not f.is_valid():
                forms_valid = False
        if form_valid and form_s_valid and forms_valid:
            form.save()
            for f in forms:
                f.save()
            form_s.save()
            return HttpResponseRedirect(reverse(myemployees))
    else:
        form = EmployeeForm(instance=employee)
        qs = EmployeeWorkingHours.objects.filter(employee=employee)
        EmployeeWorkingHoursFormSet.form = staticmethod(curry(EmployeeWorkingHoursForm, employee=employee))
        forms = EmployeeWorkingHoursFormSet(queryset=qs)
        form_s = EmployeeServicesForm(service_provider=provider, employee=employee, data=services)
    return render_to_response('employees/edit.html', locals(), context_instance=RequestContext(request))
Ejemplo n.º 15
0
 def contribute_to_class(self, cls, name):
     assert not hasattr(cls._meta, 'has_ordering_field'), "A model can't have more than one OrderingField."
     super(OrderingField, self).contribute_to_class(cls, name)
     setattr(cls._meta, 'has_ordering_field', True)
     setattr(cls._meta, 'ordering_field', self)
     setattr(cls, 'move_up', curry(cls._move_up_or_down, is_up=True))
     setattr(cls, 'move_down', curry(cls._move_up_or_down, is_up=False))
Ejemplo n.º 16
0
    def _prepare(cls):
        """
        Creates some methods once self._meta has been populated.
        """
        opts = cls._meta
        opts._prepare(cls)

        if opts.order_with_respect_to:
            cls.get_next_in_order = curry(cls._get_next_or_previous_in_order, is_next=True)
            cls.get_previous_in_order = curry(cls._get_next_or_previous_in_order, is_next=False)
            setattr(
                opts.order_with_respect_to.rel.to, "get_%s_order" % cls.__name__.lower(), curry(method_get_order, cls)
            )
            setattr(
                opts.order_with_respect_to.rel.to, "set_%s_order" % cls.__name__.lower(), curry(method_set_order, cls)
            )

        # Give the class a docstring -- its definition.
        if cls.__doc__ is None:
            cls.__doc__ = "%s(%s)" % (cls.__name__, ", ".join([f.attname for f in opts.fields]))

        if hasattr(cls, "get_absolute_url"):
            cls.get_absolute_url = update_wrapper(
                curry(get_absolute_url, opts, cls.get_absolute_url), cls.get_absolute_url
            )

        signals.class_prepared.send(sender=cls)
Ejemplo n.º 17
0
 def _contribute_thumbnail(self, cls, name, thumbnail):
     func = curry(_get_thumbnail, field=self, attrs=thumbnail)
     tag_func = curry(_get_thumbnail_tag, field=self, attrs=thumbnail)
     # Make it safe for contrib.admin
     tag_func.allow_tags = True
     setattr(cls, 'get_%s_thumbnail' % name, func)
     setattr(cls, 'get_%s_thumbnail_tag' % name, tag_func)
Ejemplo n.º 18
0
    def test_moved_object(self):
        obj_a = EventPageSpeaker(
            first_name="Father",
            last_name="Christmas",
            sort_order=1,
        )

        obj_b = EventPageSpeaker(
            first_name="Father",
            last_name="Christmas",
            sort_order=5,
        )

        comparison = self.comparison_class(
            EventPageSpeaker,
            [
                curry(self.field_comparison_class, EventPageSpeaker._meta.get_field('first_name')),
                curry(self.field_comparison_class, EventPageSpeaker._meta.get_field('last_name')),
            ],
            obj_a,
            obj_b,
        )

        self.assertFalse(comparison.is_addition())
        self.assertFalse(comparison.is_deletion())
        self.assertFalse(comparison.has_changed())
        self.assertEqual(comparison.get_position_change(), 4)
        self.assertEqual(comparison.get_num_differences(), 0)
Ejemplo n.º 19
0
def carousel(context, contents, min_photos=5, max_photos=50):
    """
    This will put a carousel of destination and tourists resource images. "contents" parameter has to be a queryset of BaseContent objects

    Example usage::

        {% load slide_tags %}
        {% block content %}
          {% secundary_carousel location resources %}
        {% endblock %}
    """

    excludes = {'main_image': ''}

    relative_contents = contents.exclude(**excludes).extra(select={'RANDOM': "RANDOM()"}).distinct().order_by("?")
    photos_bag = PhotosBag(min_photos, max_photos)

    photos_bag.add_collector(curry(_add_main_photos_relative_content, relative_contents))
    photos_bag.add_collector(curry(_add_second_photos, relative_contents))

    photos = photos_bag.collect_photos()

    return {'photos': photos,
            'MEDIA_URL': context.get('MEDIA_URL', '/media/'),
            'LANGUAGE_CODE': context.get('LANGUAGE_CODE', 'es'),
            'request': context.get('request', None)}
Ejemplo n.º 20
0
 def setUp(self):
     self.client.put = curry(self.client.post, REQUEST_METHOD='PUT')
     self.client.delete = curry(self.client.get, REQUEST_METHOD='DELETE')
     self.headers = {'HTTP_AUTHORIZATION': 'Basic %s' % b2a_base64('rest:rest')[:-1]}
     self.advancedheaders = {'HTTP_AUTHORIZATION': 'Basic %s' % b2a_base64('restadvanced:restadvanced')[:-1]}
     self.adminheaders = {'HTTP_AUTHORIZATION': 'Basic %s' % b2a_base64('restadmin:restadmin')[:-1]}	
     set_permissions()
Ejemplo n.º 21
0
def authorize_login(request):
    initial = {}
    login_url = 'get_login_view'

    if request.method == "POST":
        form = curry(Login, request)
    else:
        form = curry(Login, initial=initial)

    extra_context = {'redirect_field_name': REDIRECT_FIELD_NAME}

    if request.is_ajax():
        template_name = 'auth/_login.html'
        extra_context['hide'] = True
    else:
        template_name = login_url

    django_login(request,
                template_name=login_url,
                authentication_form=form,
                extra_context=extra_context)

    if request.user.is_authenticated():
        set_session_from_user(request, request.user)

    redirect = request.POST.get('next', None) or login_url
    return shortcuts.redirect(redirect)
Ejemplo n.º 22
0
 def contribute_to_class(self, cls, name):
     super(FileField, self).contribute_to_class(cls, name)
     setattr(cls, 'get_%s_filename' % self.name, curry(cls._get_FIELD_filename, field=self))
     setattr(cls, 'get_%s_url' % self.name, curry(cls._get_FIELD_url, field=self))
     setattr(cls, 'get_%s_size' % self.name, curry(cls._get_FIELD_size, field=self))
     setattr(cls, 'save_%s_file' % self.name, lambda instance, filename, raw_contents, save=True: instance._save_FIELD_file(self, filename, raw_contents, save))
     dispatcher.connect(self.delete_file, signal=signals.post_delete, sender=cls)
Ejemplo n.º 23
0
def login(request):
    """ Logs a user in using the :class:`~openstack_auth.forms.Login` form. """
    # Get our initial region for the form.
    initial = {}
    current_region = request.session.get("region_endpoint", None)
    requested_region = request.GET.get("region", None)
    regions = dict(getattr(settings, "AVAILABLE_REGIONS", []))
    if requested_region in regions and requested_region != current_region:
        initial.update({"region": requested_region})

    if request.method == "POST":
        form = curry(Login, request)
    else:
        form = curry(Login, initial=initial)

    extra_context = {"redirect_field_name": REDIRECT_FIELD_NAME}

    if request.is_ajax():
        template_name = "auth/_login.html"
        extra_context["hide"] = True
    else:
        template_name = "auth/login.html"

    res = django_login(request, template_name=template_name, authentication_form=form, extra_context=extra_context)
    # Set the session data here because django's session key rotation
    # will erase it if we set it earlier.
    if request.user.is_authenticated():
        set_session_from_user(request, request.user)
        regions = dict(Login.get_region_choices())
        region = request.user.endpoint
        region_name = regions.get(region)
        request.session["region_endpoint"] = region
        request.session["region_name"] = region_name
    return res
Ejemplo n.º 24
0
    def __init__(self, field, obj):
        self.field = field
        self.parent_obj = obj
        self.original_image = getattr(self.parent_obj, self.field.attname)
        self.original_image_path = os.path.join(settings.MEDIA_ROOT, str(self.original_image))
        self.mangled_name = str(self.original_image) # md5.new('sehkr1tt-%s-%r-%r' % (str(self.original_image), time.time(), id(self))).hexdigest()
        self.scaled_image_base = os.path.join(settings.MEDIA_ROOT, ',', self.mangled_name)
        self.broken_image = None

        # imageid is used for webstorage
        self.imageid = None

        # if broken.gif exists we send that if there are any problems during scaling
        if not os.path.exists(self.original_image_path):
            # check if we are using web based storage
            imageid = str(self.original_image)
            if imageid in huimages._setup_couchdb():
                self.original_image_path = huimages.imageurl(imageid)
                self.imageid = imageid
            else:
                self.broken_image = os.path.join(settings.MEDIA_ROOT, 'broken.gif') 

        for size in _sizes:
            setattr(self, '%s_path' % (size), curry(self.scaled_filename, size))
            setattr(self, '%s' % (size), curry(self.scaled_url, size))
            setattr(self, '%s_dimensions' % (size), curry(self.scaled_dimensions, size))
            setattr(self, '%s_tag' % (size), curry(self.scaled_tag, size))
Ejemplo n.º 25
0
 def __init__(self, queryset, responder, receiver=None, authentication=None,
              permitted_methods=None, expose_fields=None, entry_class=None,
              form_class=None):
     """
     queryset:
         determines the subset of objects (of a Django model)
         that make up this resource
     responder:
         the data format instance that creates HttpResponse
         objects from single or multiple model objects and
         renders forms
     receiver:
         the data format instance that handles POST and
         PUT data
     authentication:
         the authentication instance that checks whether a
         request is authenticated
     permitted_methods:
         the HTTP request methods that are allowed for this 
         resource e.g. ('GET', 'PUT')
     expose_fields:
         the model fields that can be accessed
         by the HTTP methods described in permitted_methods
     entry_class:
         class used for entries in create() and get_entry();
         default: class Entry (see below)
     form_class:
         base form class used for data validation and
         conversion in self.create() and Entry.update()
     """
     # Available data
     self.queryset = queryset
     
     # Input format
     if not receiver:
         receiver = FormReceiver()
     self.receiver = receiver
     
     # Input validation
     if not form_class:
         form_class = ModelForm
     self.form_class = form_class
     
     # Output format / responder setup
     self.responder = responder
     if not expose_fields:
         expose_fields = [field.name for field in queryset.model._meta.fields]
     responder.expose_fields = expose_fields
     if hasattr(responder, 'create_form'):
         responder.create_form = curry(responder.create_form, queryset=queryset, form_class=form_class)
     if hasattr(responder, 'update_form'):
         responder.update_form = curry(responder.update_form, queryset=queryset, form_class=form_class)
     
     # Resource class for individual objects of the collection
     if not entry_class:
         entry_class = Entry
     self.entry_class = entry_class
     
     ResourceBase.__init__(self, authentication, permitted_methods)
Ejemplo n.º 26
0
def get_mapping(model_or_queryset):
    '''Get the mapping for a given model or queryset'''
    mappings = get_mappings()

    if isinstance(model_or_queryset, models.query.QuerySet):
        queryset = model_or_queryset
        model = model_or_queryset.model
    elif issubclass(model_or_queryset, models.Model):
        queryset = model_or_queryset.objects.all()
        model = model_or_queryset
    else:
        raise TypeError(
            'Only `django.db.model.Model` and `django.db.query.QuerySet` '
            'objects are valid arguments')

    meta = model._meta
    mapping_key = meta.app_label + '.' + meta.object_name

    mapping = mappings.get(mapping_key)
    if mapping is not None:
        mapping = mapping.copy()
    else:
        raise exceptions.MappingUndefined('Unable to find mapping '
                                          'for %s' % mapping_key)

    # The callable allows for customizing the queryset on the fly
    queryset = mapping.get('queryset', queryset)
    if callable(queryset):
        queryset = queryset(mapping)

    mapping['app'] = meta.app_label
    mapping['model'] = meta.object_name
    mapping['queryset'] = queryset
    mapping.setdefault('separator', ' - ')

    if 'field' in mapping:
        mapping['fields'] = mapping['field'],
    elif 'fields' not in mapping:
        raise exceptions.ConfigurationError(
            'Every mapping should have a field or fields attribute. Mapping: '
            '%r' % mapping)

    mapping.setdefault('split_func', curry(
        mapping.get('split_func', split_func),
        mapping['fields'],
        mapping['separator'],
    ))
    mapping.setdefault('join_func', curry(
        mapping.get('join_func', join_func),
        mapping['fields'],
        mapping['separator'],
    ))
    mapping.setdefault('filter_func', curry(
        mapping.get('filter_func', filter_func),
        mapping['fields'],
        mapping['separator'],
    ))

    return mapping.copy()
Ejemplo n.º 27
0
def edit_coordinator(request, coordinator):
  history = History.objects.filter(submitter=request.user, job=coordinator).order_by('-submission_date')

  DatasetFormSet = inlineformset_factory(Coordinator, Dataset, form=DatasetForm, max_num=0, can_order=False, can_delete=True)
  DataInputFormSet = inlineformset_factory(Coordinator, DataInput, form=DataInputForm, max_num=0, can_order=False, can_delete=True)
  DataInputFormSet.form = staticmethod(curry(DataInputForm, coordinator=coordinator))
  DataOutputFormSet = inlineformset_factory(Coordinator, DataOutput, form=DataOutputForm, max_num=0, can_order=False, can_delete=True)
  DataOutputFormSet.form = staticmethod(curry(DataOutputForm, coordinator=coordinator))

  dataset = Dataset(coordinator=coordinator)
  dataset_form = DatasetForm(instance=dataset, prefix='create')

  NewDataInputFormSet = inlineformset_factory(Coordinator, DataInput, form=DataInputForm, extra=0, can_order=False, can_delete=False)
  NewDataInputFormSet.form = staticmethod(curry(DataInputForm, coordinator=coordinator))
  NewDataOutputFormSet = inlineformset_factory(Coordinator, DataOutput, form=DataOutputForm, extra=0, can_order=False, can_delete=False)
  NewDataOutputFormSet.form = staticmethod(curry(DataOutputForm, coordinator=coordinator))

  if request.method == 'POST':
    coordinator_form = CoordinatorForm(request.POST, instance=coordinator, user=request.user)
    dataset_formset = DatasetFormSet(request.POST, request.FILES, instance=coordinator)
    data_input_formset = DataInputFormSet(request.POST, request.FILES, instance=coordinator)
    data_output_formset = DataOutputFormSet(request.POST, request.FILES, instance=coordinator)
    new_data_input_formset = NewDataInputFormSet(request.POST, request.FILES, instance=coordinator, prefix='input')
    new_data_output_formset = NewDataOutputFormSet(request.POST, request.FILES, instance=coordinator, prefix='output')

    if coordinator_form.is_valid() and dataset_formset.is_valid() and data_input_formset.is_valid() and data_output_formset.is_valid() \
        and new_data_input_formset.is_valid() and new_data_output_formset.is_valid():
      coordinator = coordinator_form.save()
      dataset_formset.save()
      data_input_formset.save()
      data_output_formset.save()
      new_data_input_formset.save()
      new_data_output_formset.save()

      coordinator.sla = json.loads(request.POST.get('sla'))
      coordinator.save()

      request.info(_('Coordinator saved.'))
      return redirect(reverse('oozie:edit_coordinator', kwargs={'coordinator': coordinator.id}))
  else:
    coordinator_form = CoordinatorForm(instance=coordinator, user=request.user)
    dataset_formset = DatasetFormSet(instance=coordinator)
    data_input_formset = DataInputFormSet(instance=coordinator)
    data_output_formset = DataOutputFormSet(instance=coordinator)
    new_data_input_formset = NewDataInputFormSet(queryset=DataInput.objects.none(), instance=coordinator, prefix='input')
    new_data_output_formset = NewDataOutputFormSet(queryset=DataOutput.objects.none(), instance=coordinator, prefix='output')

  return render('editor/edit_coordinator.mako', request, {
    'coordinator': coordinator,
    'coordinator_form': coordinator_form,
    'dataset_formset': dataset_formset,
    'data_input_formset': data_input_formset,
    'data_output_formset': data_output_formset,
    'dataset': dataset,
    'dataset_form': dataset_form,
    'new_data_input_formset': new_data_input_formset,
    'new_data_output_formset': new_data_output_formset,
    'history': history
  })
Ejemplo n.º 28
0
 def contribute_to_class(self, cls, name):
     super(ImageField, self).contribute_to_class(cls, name)
     # Add get_BLAH_width and get_BLAH_height methods, but only if the
     # image field doesn't have width and height cache fields.
     if not self.width_field:
         setattr(cls, 'get_%s_width' % self.name, curry(cls._get_FIELD_width, field=self))
     if not self.height_field:
         setattr(cls, 'get_%s_height' % self.name, curry(cls._get_FIELD_height, field=self))
Ejemplo n.º 29
0
def organisation(request, org_pk):
    """
    Expenses for organisation
    """
    org = Organisation.objects.get(pk=org_pk)
    expenses = Expense.objects.filter(token__user=request.user,
                                      project__organisation=org).order_by('-time')
    p = Paginator(expenses, 10)
    page = p.page(request.GET.get('p', 1))

    OExpFormset = formset_factory(OfficialExpenseForm)
    # Use curry to get the form specifically for the organisation
    OExpFormset.form = staticmethod(curry(OfficialExpenseForm, org))

    if request.method == 'POST':
        formset = OExpFormset(request.POST, request.FILES)

        if formset.is_valid():
            for form in formset:
                expense = form.save(commit=False)
                token = AuthToken.objects.get_or_create(user=request.user,
                                                    site_token=True)[0]
                expense.token = token
                if expense.billed:
                    # If expense is billed, create a bill ID in this format:
                    # <user_id><proj_id><token_id><count>
                    expense.bill_id = '%s%s%s%s' %(token.user.id, expense.project.id,
                                                   token.id,
                                                   expenses.filter(token=token,
                                                                    billed=True).count()+1)
                expense.save()

            return redirect(org)
    else:
        initial = {
        }
        try:
            # Fill up the initial data
            latest = expenses.latest()
            initial['location'] = latest.location
            initial['category']=latest.category
            initial['project']=latest.project

        except Expense.DoesNotExist:
            pass

        # Use the curry utility to pass initial data to forms in
        # the formset
        OExpFormset.form = staticmethod(curry(OfficialExpenseForm, org,
                                              initial=initial))
        formset = OExpFormset()

    return render(request, 'main/organisation.html', {
                                                'organisation':org,
                                                'page':page,
                                                'formset':formset,
                                            })
Ejemplo n.º 30
0
def fogbow_Login(request, template_name=None, extra_context=None, **kwargs):
    formChosen = ''
    formReference = AllForm
    
    initial = {}
    if formChosen == IPConstants.AUTH_KEYSTONE:
        if (request.user.is_authenticated() and
            auth.REDIRECT_FIELD_NAME not in request.GET and
            auth.REDIRECT_FIELD_NAME not in request.POST):
            return shortcuts.redirect(settings.LOGIN_REDIRECT_URL)
    
        current_region = request.session.get('region_endpoint', None)
        requested_region = request.GET.get('region', None)
        regions = dict(getattr(settings, 'AVAILABLE_REGIONS', []))
        if requested_region in regions and requested_region != current_region:
            initial.update({'region': requested_region})
    
    if request.method == "POST":                
        if django.VERSION >= (1, 6):
            form = functional.curry(formReference)
        else:
            form = functional.curry(formReference, request)
    else:
        form = functional.curry(formReference, initial=initial)
        
    if not template_name:
        if request.is_ajax():
            template_name = 'auth/fogbow_login.html'
            extra_context['hide'] = True
        else:
            template_name = 'auth/fogbowlogin.html'
            
    if extra_context is None:
        extra_context = {'redirect_field_name': auth.REDIRECT_FIELD_NAME}
        
    extra_context.update(getContextForm())
    del extra_context['form']               

    res = django_auth_views.login(request,
                                  template_name=template_name,
                                  authentication_form=form,
                                  extra_context=extra_context,
                                  **kwargs)
    
    if request.user.is_authenticated():
        if formChosen == IPConstants.AUTH_KEYSTONE:
            auth_user.set_session_from_user(request, request.user)
            regions = dict(forms.Login.get_region_choices())
            region = request.user.endpoint
            region_name = regions.get(region)
            request.session['region_endpoint'] = region
            request.session['region_name'] = region_name        
        else:  
            request._cached_user = request.user
            request.user = request.user
                    
    return res
Ejemplo n.º 31
0
 def get_form(self, *args, **kwargs):
     form = super(PageAdmin, self).get_form(*args, **kwargs)
     return curry(form, modeladmin=self)
Ejemplo n.º 32
0
def login(request, template_name=None, extra_context=None, **kwargs):
    """Logs a user in using the :class:`~openstack_auth.forms.Login` form."""

    # If the user enabled websso and the default redirect
    # redirect to the default websso url
    if (request.method == 'GET' and utils.is_websso_enabled
            and utils.is_websso_default_redirect()):
        protocol = utils.get_websso_default_redirect_protocol()
        region = utils.get_websso_default_redirect_region()
        origin = request.build_absolute_uri('/auth/websso/')
        url = ('%s/auth/OS-FEDERATION/websso/%s?origin=%s' %
               (region, protocol, origin))
        return shortcuts.redirect(url)

    # If the user enabled websso and selects default protocol
    # from the dropdown, We need to redirect user to the websso url
    if request.method == 'POST':
        auth_type = request.POST.get('auth_type', 'credentials')
        if utils.is_websso_enabled() and auth_type != 'credentials':
            auth_url = getattr(settings, 'WEBSSO_KEYSTONE_URL',
                               request.POST.get('region'))
            url = utils.get_websso_url(request, auth_url, auth_type)
            return shortcuts.redirect(url)

    if not request.is_ajax():
        # If the user is already authenticated, redirect them to the
        # dashboard straight away, unless the 'next' parameter is set as it
        # usually indicates requesting access to a page that requires different
        # permissions.
        if (request.user.is_authenticated
                and auth.REDIRECT_FIELD_NAME not in request.GET
                and auth.REDIRECT_FIELD_NAME not in request.POST):
            return shortcuts.redirect(settings.LOGIN_REDIRECT_URL)

    # Get our initial region for the form.
    initial = {}
    current_region = request.session.get('region_endpoint', None)
    requested_region = request.GET.get('region', None)
    regions = dict(getattr(settings, "AVAILABLE_REGIONS", []))
    if requested_region in regions and requested_region != current_region:
        initial.update({'region': requested_region})

    if request.method == "POST":
        form = functional.curry(forms.Login)
    else:
        form = functional.curry(forms.Login, initial=initial)

    if extra_context is None:
        extra_context = {'redirect_field_name': auth.REDIRECT_FIELD_NAME}

    extra_context['csrf_failure'] = request.GET.get('csrf_failure')

    choices = getattr(settings, 'WEBSSO_CHOICES', ())
    extra_context['show_sso_opts'] = (utils.is_websso_enabled()
                                      and len(choices) > 1)

    if not template_name:
        if request.is_ajax():
            template_name = 'auth/_login.html'
            extra_context['hide'] = True
        else:
            template_name = 'auth/login.html'

    res = django_auth_views.login(request,
                                  template_name=template_name,
                                  authentication_form=form,
                                  extra_context=extra_context,
                                  **kwargs)
    # Save the region in the cookie, this is used as the default
    # selected region next time the Login form loads.
    if request.method == "POST":
        utils.set_response_cookie(res, 'login_region',
                                  request.POST.get('region', ''))
        utils.set_response_cookie(res, 'login_domain',
                                  request.POST.get('domain', ''))

    # Set the session data here because django's session key rotation
    # will erase it if we set it earlier.
    if request.user.is_authenticated:
        auth_user.set_session_from_user(request, request.user)
        regions = dict(forms.Login.get_region_choices())
        region = request.user.endpoint
        login_region = request.POST.get('region')
        region_name = regions.get(login_region)
        request.session['region_endpoint'] = region
        request.session['region_name'] = region_name
        expiration_time = request.user.time_until_expiration()
        threshold_days = getattr(settings,
                                 'PASSWORD_EXPIRES_WARNING_THRESHOLD_DAYS', -1)
        if expiration_time is not None and \
                expiration_time.days <= threshold_days:
            expiration_time = str(expiration_time).rsplit(':', 1)[0]
            msg = (_('Please consider changing your password, it will expire'
                     ' in %s minutes') % expiration_time).replace(
                         ':', ' Hours and ')
            messages.warning(request, msg)
    return res
Ejemplo n.º 33
0
from rest_framework.decorators import detail_route
from rest_framework.response import Response
from wagtail.wagtailadmin import messages

from variables.models import Variable, RasterRequest
from variables.serializers import VariableSerializer, RasterRequestSerializer
from variables.data import NODE_TYPES, JobIncompleteException, rpc_con

from django.core.serializers.json import DjangoJSONEncoder
from django.utils.functional import curry
from datetime import date, timedelta
import json
from psycopg2.extras import DateRange
from numpy import isnan

json.dumps = curry(json.dumps, cls=DjangoJSONEncoder)


def get_raster_catalog():
    if not hasattr(settings, 'RPC_URL'):
        print "Error: RPC_URL must be set in settings.py"

    try:
        conn = rpc_con()
        data = conn.get_catalog()

        if not data:
            return []

        for r in data:
            r['start_date'] = r['start_date'].date()
Ejemplo n.º 34
0
 def bulk_chown(*args, **kwargs):
     op = curry(request.fs.chown, recursive=request.POST.get('recursive', False))
     for arg in args:
         varg = [arg[param] for param in param_names]
         op(*varg)
Ejemplo n.º 35
0
    def get_mass_upload_context(self, request):
        model = self.model
        opts = model._meta
        self.register_newman_variables(request)

        # To enable admin-specific fields, we need to run the form class
        # through modelform_factory using curry
        FormClass = modelform_factory(
            Photo,
            form=MassUploadForm,
            fields=flatten_fieldsets(self.mass_upload_fieldsets),
            formfield_callback=curry(self.formfield_for_dbfield,
                                     request=request))

        context = {}
        if request.method == 'POST':
            error_dict = {}
            # Unfortunately, FLASH uploader sends array data in weird format
            # so that Django doesn't recognize it as array of values, but
            # as one string with commas inside. The only way to expect it
            # and preprocess the values by ourselves.
            data = dict((key, val) for key, val in request.POST.items())
            form = FormClass(data, request.FILES)

            if form.is_valid():
                # To prevent newman from handling our field by common flash editor
                # we need to use a different mechanism
                new_object = form.save(commit=False)
                new_object.image = form.cleaned_data['image_file']
                new_object.save()
                form.save_m2m()
                context.update({'object': new_object})
            else:
                for e in form.errors:
                    error_dict[u"id_%s" %
                               e] = [u"%s" % ee for ee in form.errors[e]]
                context.update({'error_dict': error_dict})
        else:
            form = FormClass()

        adminForm = helpers.AdminForm(form, list(self.mass_upload_fieldsets),
                                      self.prepopulated_fields)
        massUploadForm = helpers.AdminForm(form,
                                           list(self.mass_upload2_fieldsets),
                                           self.prepopulated_fields)
        media = self.media + adminForm.media

        context.update({
            'title':
            _('Mass upload'),
            'adminform':
            adminForm,
            'mass_upload2_form':
            massUploadForm,
            'is_popup':
            request.REQUEST.has_key('_popup'),
            'show_delete':
            False,
            'media':
            media,
            'inline_admin_formsets': [],
            'errors':
            helpers.AdminErrorList(form, ()),
            'root_path':
            self.admin_site.root_path,
            'app_label':
            opts.app_label,
            'opts':
            opts,
            'has_change_permission':
            self.has_change_permission(request, None),
            'raw_form':
            form
        })
        return context
Ejemplo n.º 36
0
        serializers.serialize(format, [obj], indent=2, stream=stream)

        # Serialize normally for a comparison
        string_data = serializers.serialize(format, [obj], indent=2)

        # Check that the two are the same
        if isinstance(stream, six.StringIO):
            self.assertEqual(string_data, stream.getvalue())
        else:
            self.assertEqual(string_data, stream.content.decode('utf-8'))
        stream.close()


for format in serializers.get_serializer_formats():
    setattr(SerializerTests, 'test_' + format + '_serializer',
            curry(serializerTest, format))
    setattr(SerializerTests, 'test_' + format + '_natural_key_serializer',
            curry(naturalKeySerializerTest, format))
    setattr(SerializerTests, 'test_' + format + '_serializer_fields',
            curry(fieldsTest, format))
    if format != 'python':
        setattr(SerializerTests, 'test_' + format + '_serializer_stream',
                curry(streamTest, format))


class XmlDeserializerSecurityTests(TestCase):
    def test_no_dtd(self):
        """
        The XML deserializer shouldn't allow a DTD.

        This is the most straightforward way to prevent all entity definitions
Ejemplo n.º 37
0
    objects = []
    transaction.enter_transaction_management()
    transaction.managed(True)
    for (func, pk, klass, datum) in test_data:
        objects.append(func[0](pk, klass, datum))
    transaction.commit()
    transaction.leave_transaction_management()

    # Add the generic tagged objects to the object list
    objects.extend(Tag.objects.all())

    # Serialize the test database
    serialized_data = serializers.serialize(format, objects, indent=2)

    # Flush the database and recreate from the serialized data
    management.flush(verbosity=0, interactive=False)
    transaction.enter_transaction_management()
    transaction.managed(True)
    for obj in serializers.deserialize(format, serialized_data):
        obj.save()
    transaction.commit()
    transaction.leave_transaction_management()

    # Assert that the deserialized data is the same
    # as the original source
    for (func, pk, klass, datum) in test_data:
        func[1](self, pk, klass, datum)

for format in serializers.get_serializer_formats():
    setattr(SerializerTests, 'test_'+format+'_serializer', curry(serializerTest, format))
Ejemplo n.º 38
0
def edit_choices(request, event_id):

    event = Event.objects.get(id=event_id)
    # Get all previously made choices for this event
    previous_choices = ApplicationChoices.objects.filter(
        person=request.user, event=event_id).order_by("choice_number")

    max_num = event.allowed_choice_num
    extra = event.allowed_choice_num - previous_choices.count()

    # example: initial = [{"choice": "1"}, {"choice": "2"}]
    initial = []
    # Previous choices of the user must come pre-selected in edit form
    for choice in previous_choices:
        initial.append({"choice": str(choice.choice.id)})

    # example: choices = [("1","1"), ("2","2")]
    choices = []

    # Remove applied course from possible choices for this event
    try:
        applied_course = Application.objects.get(person=request.user,
                                                 course__event=event_id)
    except Application.DoesNotExist:
        messages.error(request,
                       _('You did not apply to any course in this event!'))
        return render_to_response('kurs/hata.html',
                                  context_instance=RequestContext(request))

    # FIXME: use only courses that are open for application
    courses = Course.objects.filter(event=event_id).exclude(
        id=applied_course.course.id)
    for course in courses:
        choices.append((course.id, course.display_name))

    # initialize form according to allowed_choice_num for the event
    # the reason we use formset here instead of a regular form is
    # we do now know in advance how many allowed_choice_num there will be
    # for a given event. Since the number is dynamic (coming from model/DB)
    # we have to use formset and generate necessary number of choice drop-down
    formset = formset_factory(ApplicationChoiceForm,
                              max_num=max_num,
                              extra=extra)
    formset.form = staticmethod(curry(ApplicationChoiceForm, choices=choices))

    if request.method == 'POST':
        EditChoicesFormSet = formset(request.POST, request.FILES)
        if EditChoicesFormSet.is_valid():
            # Delete all choices made previously in order to overwrite
            if not previous_choices.count() == 0:
                for prev_choices in previous_choices:

                    if logger.isEnabledFor(logging.DEBUG):
                        logger.debug(
                            "Tercih silindi: %s , request.user='******' , request.META['REMOTE_ADDR']='%s'"
                            % (prev_choices, request.user,
                               request.META["REMOTE_ADDR"]))

                previous_choices.delete()

            # save all applicationchoices of user to the DB
            choice_number = 1
            for choices in EditChoicesFormSet.cleaned_data:
                record = ApplicationChoices(
                    person=request.user,
                    event=Event.objects.get(id=event_id),
                    choice_number=choice_number,
                    choice=Course.objects.get(id=choices["choice"]))
                record.save()

                if logger.isEnabledFor(logging.DEBUG):
                    logger.debug(
                        "Tercih yapıldı: %s , request.user='******' , request.META['REMOTE_ADDR']='%s'"
                        % (record, request.user, request.META["REMOTE_ADDR"]))

                choice_number += 1

            messages.info(request, _('Your choices are saved'))
            # redirect to his applicationchoice list for this event
            return HttpResponseRedirect("/kurs/etkinlik/" + event_id +
                                        "/tercihler/")

    else:
        return render_to_response('kurs/applicationchoices_edit.html',
                                  {'formset': formset(initial=initial)},
                                  context_instance=RequestContext(request))
Ejemplo n.º 39
0
 def bulk_chmod(*args, **kwargs):
     op = curry(request.fs.chmod, recursive=request.POST.get('recursive', False))
     for arg in args:
         op(arg['path'], arg['mode'])
Ejemplo n.º 40
0
def edit_coordinator(request, coordinator):
    history = History.objects.filter(
        submitter=request.user, job=coordinator).order_by('-submission_date')

    DatasetFormSet = inlineformset_factory(Coordinator,
                                           Dataset,
                                           form=DatasetForm,
                                           max_num=0,
                                           can_order=False,
                                           can_delete=True)
    DataInputFormSet = inlineformset_factory(Coordinator,
                                             DataInput,
                                             form=DataInputSetForm,
                                             max_num=0,
                                             can_order=False,
                                             can_delete=True)
    DataOutputFormSet = inlineformset_factory(Coordinator,
                                              DataOutput,
                                              form=DataOutputSetForm,
                                              max_num=0,
                                              can_order=False,
                                              can_delete=True)

    dataset = Dataset(coordinator=coordinator)
    dataset_form = DatasetForm(instance=dataset, prefix='create')

    NewDataInputFormSet = inlineformset_factory(Coordinator,
                                                DataInput,
                                                form=DataInputForm,
                                                extra=0,
                                                can_order=False,
                                                can_delete=False)
    NewDataInputFormSet.form = staticmethod(
        curry(DataInputForm, coordinator=coordinator))
    NewDataOutputFormSet = inlineformset_factory(Coordinator,
                                                 DataOutput,
                                                 form=DataOutputForm,
                                                 extra=0,
                                                 can_order=False,
                                                 can_delete=False)
    NewDataOutputFormSet.form = staticmethod(
        curry(DataOutputForm, coordinator=coordinator))

    if request.method == 'POST':
        coordinator_form = CoordinatorForm(request.POST,
                                           instance=coordinator,
                                           user=request.user)
        dataset_formset = DatasetFormSet(request.POST,
                                         request.FILES,
                                         instance=coordinator)
        data_input_formset = DataInputFormSet(request.POST,
                                              request.FILES,
                                              instance=coordinator)
        data_output_formset = DataOutputFormSet(request.POST,
                                                request.FILES,
                                                instance=coordinator)
        new_data_input_formset = NewDataInputFormSet(request.POST,
                                                     request.FILES,
                                                     instance=coordinator,
                                                     prefix='input')
        new_data_output_formset = NewDataOutputFormSet(request.POST,
                                                       request.FILES,
                                                       instance=coordinator,
                                                       prefix='output')

        if coordinator_form.is_valid() and dataset_formset.is_valid() and data_input_formset.is_valid() and data_output_formset.is_valid() \
            and new_data_input_formset.is_valid() and new_data_output_formset.is_valid():
            coordinator = coordinator_form.save()
            dataset_formset.save()
            data_input_formset.save()
            data_output_formset.save()
            new_data_input_formset.save()
            new_data_output_formset.save()

            request.info(_('Coordinator saved!'))
            return redirect(
                reverse('oozie:edit_coordinator',
                        kwargs={'coordinator': coordinator.id}))
    else:
        coordinator_form = CoordinatorForm(instance=coordinator,
                                           user=request.user)
        dataset_formset = DatasetFormSet(instance=coordinator)
        data_input_formset = DataInputFormSet(instance=coordinator)
        data_output_formset = DataOutputFormSet(instance=coordinator)
        new_data_input_formset = NewDataInputFormSet(
            queryset=DataInput.objects.none(),
            instance=coordinator,
            prefix='input')
        new_data_output_formset = NewDataOutputFormSet(
            queryset=DataOutput.objects.none(),
            instance=coordinator,
            prefix='output')

    return render(
        'editor/edit_coordinator.mako', request, {
            'coordinator': coordinator,
            'coordinator_form': coordinator_form,
            'dataset_formset': dataset_formset,
            'data_input_formset': data_input_formset,
            'data_output_formset': data_output_formset,
            'dataset_form': dataset_form,
            'new_data_input_formset': new_data_input_formset,
            'new_data_output_formset': new_data_output_formset,
            'history': history,
            'parameters': extract_field_data(coordinator_form['parameters'])
        })
Ejemplo n.º 41
0
 def get_formset(self, request, obj=None, **kwargs):
     formset = super(TrackInline, self).get_formset(request, obj, **kwargs)
     if request.method == 'GET':
         formset.__init__ = curry(formset.__init__, initial=self.initial)
     return formset
Ejemplo n.º 42
0
 def get_formset(self, request, obj=None, **kwargs):
     formset = super(RequestProvidingModelAdminMixin, self).\
         get_formset(request, obj, **kwargs)
     formset.form.__init__ = curry(formset.form.__init__, request=request)
     return formset
Ejemplo n.º 43
0
 def get_manipulator_field_objs(self):
     choices = self.get_choices_default()
     return [curry(oldforms.SelectMultipleField, size=min(max(len(choices), 5), 15), choices=choices)]
Ejemplo n.º 44
0
 def __init__(self, request):
     for name in self.API:
         api_fn = getattr(messages.api, name)
         setattr(self, name, curry(api_fn, request))
Ejemplo n.º 45
0
    def request(self, **request):
        """
        The master request method. Composes the environment dictionary
        and passes to the handler, returning the result of the handler.
        Assumes defaults for the query environment, which can be overridden
        using the arguments to the request.
        """
        environ = self._base_environ(**request)

        # Curry a data dictionary into an instance of the template renderer
        # callback function.
        data = {}
        on_template_render = curry(store_rendered_templates, data)
        signal_uid = "template-render-%s" % id(request)
        signals.template_rendered.connect(on_template_render, dispatch_uid=signal_uid)
        # Capture exceptions created by the handler.
        exception_uid = "request-exception-%s" % id(request)
        got_request_exception.connect(self.store_exc_info, dispatch_uid=exception_uid)
        try:
            try:
                response = self.handler(environ)
            except TemplateDoesNotExist as e:
                # If the view raises an exception, Django will attempt to show
                # the 500.html template. If that template is not available,
                # we should ignore the error in favor of re-raising the
                # underlying exception that caused the 500 error. Any other
                # template found to be missing during view error handling
                # should be reported as-is.
                if e.args != ('500.html',):
                    raise

            # Look for a signalled exception, clear the current context
            # exception data, then re-raise the signalled exception.
            # Also make sure that the signalled exception is cleared from
            # the local cache!
            if self.exc_info:
                exc_info = self.exc_info
                self.exc_info = None
                six.reraise(*exc_info)

            # Save the client and request that stimulated the response.
            response.client = self
            response.request = request

            # Add any rendered template detail to the response.
            response.templates = data.get("templates", [])
            response.context = data.get("context")

            response.json = curry(self._parse_json, response)

            # Attach the ResolverMatch instance to the response
            response.resolver_match = SimpleLazyObject(
                lambda: urlresolvers.resolve(request['PATH_INFO']))

            # Flatten a single context. Not really necessary anymore thanks to
            # the __getattr__ flattening in ContextList, but has some edge-case
            # backwards-compatibility implications.
            if response.context and len(response.context) == 1:
                response.context = response.context[0]

            # Update persistent cookie data.
            if response.cookies:
                self.cookies.update(response.cookies)

            return response
        finally:
            signals.template_rendered.disconnect(dispatch_uid=signal_uid)
            got_request_exception.disconnect(dispatch_uid=exception_uid)
Ejemplo n.º 46
0
 def make_foreign_order_accessors(field, model, cls):
     setattr(field.rel.to, 'get_%s_order' % cls.__name__.lower(),
             curry(method_get_order, cls))
     setattr(field.rel.to, 'set_%s_order' % cls.__name__.lower(),
             curry(method_set_order, cls))
Ejemplo n.º 47
0
 def get_manipulator_field_objs(self):
     if self.rel.raw_id_admin:
         return [forms.RawIdAdminField]
     else:
         choices = self.get_choices_default()
         return [curry(forms.CheckboxSelectMultipleField, choices=choices)]
Ejemplo n.º 48
0
from django.conf import settings
from django.conf.urls.static import static

# from djrill import DjrillAdminSite
# admin.site = DjrillAdminSite()
admin.autodiscover()
#dajaxice_autodiscover()

#from yawdadmin import admin_site
urlpatterns = patterns(
    '',
    #url(r'^admin_tools/', include('admin_tools.urls')),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^', include('apps.account_system.urls')),
    url(r'^', include('apps.establishment_system.urls')),
    url(r'^', include('apps.recommender_system.urls')),
    url(r'^', include('apps.main.urls')),
    url(r'^autocomplete/', include('autocomplete_light.urls')),
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

urlpatterns += staticfiles_urlpatterns()

if 'grappelli' in settings.INSTALLED_APPS:
    urlpatterns += patterns('', url(r'^grappelli/', include('grappelli.urls')))

from django.utils.functional import curry
from django.views.defaults import page_not_found, server_error, permission_denied
#handler404 = "apps.main.views.error404"
handler500 = curry(server_error, template_name='main/500.html')
handler404 = curry(page_not_found, template_name='main/404.html')
#handler403 = curry(permission_denied, template_name='main/403.html')
Ejemplo n.º 49
0
    def get_comparison(self):
        comparator_class = self.get_comparison_class()

        if comparator_class:
            return [curry(comparator_class, self.db_field)]
        return []
Ejemplo n.º 50
0
 def add_accessor_methods(self, *args, **kwargs):
     for contact_type, name in CONTACT_TYPES:
         setattr(self, '%s_relations' % contact_type,
                 curry(self._get_TYPE_relations, contact_type=contact_type))
Ejemplo n.º 51
0
def _get_render_func(dotted_path, **kwargs):
    # Don't coerce to unicode on python 2
    (module, func) = dotted_path.rsplit(str('.'), 1)
    func = getattr(__import__(module, {}, {}, [func]), func)
    return curry(func, **kwargs)
Ejemplo n.º 52
0
    # Check that the deserialized object contains data in only the serialized fields.
    self.assertEqual(result.object.field1, 'first')
    self.assertEqual(result.object.field2, '')
    self.assertEqual(result.object.field3, 'third')


def streamTest(format, self):
    obj = ComplexModel(field1='first', field2='second', field3='third')
    obj.save_base(raw=True)

    # Serialize the test database to a stream
    stream = StringIO()
    serializers.serialize(format, [obj], indent=2, stream=stream)

    # Serialize normally for a comparison
    string_data = serializers.serialize(format, [obj], indent=2)

    # Check that the two are the same
    self.assertEqual(string_data, stream.getvalue())
    stream.close()


for format in serializers.get_serializer_formats():
    setattr(SerializerTests, 'test_' + format + '_serializer',
            curry(serializerTest, format))
    setattr(SerializerTests, 'test_' + format + '_serializer_fields',
            curry(fieldsTest, format))
    if format != 'python':
        setattr(SerializerTests, 'test_' + format + '_serializer_stream',
                curry(streamTest, format))
Ejemplo n.º 53
0
"""shortly URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from django.views.defaults import page_not_found
from django.utils.functional import curry
from appshortly import views

handler404 = curry(page_not_found, template_name='appshortly/404.html')

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.index),
    path('<int:url_id>', views.detail_url),
    path('<int:url_id>/detail', views.view_url),
    path('create_short_url', views.create_new_url),
]
Ejemplo n.º 54
0
def edit(request,
         id,
         form_class=StudyGroupForm,
         meta_form_class=MetaForm,
         category_form_class=CategoryForm,
         template_name="studygroups/edit.html"):

    study_group = get_object_or_404(StudyGroup, pk=id)

    if not has_perm(request.user, 'studygroups.change_studygroup',
                    study_group):
        raise Http403

    content_type = get_object_or_404(ContentType,
                                     app_label='studygroups',
                                     model='studygroup')

    #setup categories
    category = Category.objects.get_for_object(study_group, 'category')
    sub_category = Category.objects.get_for_object(study_group, 'sub_category')

    initial_category_form_data = {
        'app_label': 'studygroups',
        'model': 'studygroup',
        'pk': study_group.pk,
        'category': getattr(category, 'name', '0'),
        'sub_category': getattr(sub_category, 'name', '0')
    }

    OfficerFormSet = inlineformset_factory(StudyGroup,
                                           Officer,
                                           form=OfficerForm,
                                           extra=1)
    OfficerFormSet.form = staticmethod(
        curry(OfficerForm, study_group_group=study_group.group))

    if request.method == "POST":
        form = form_class(request.POST,
                          request.FILES,
                          instance=study_group,
                          user=request.user)
        metaform = meta_form_class(request.POST,
                                   instance=study_group.meta,
                                   prefix='meta')
        categoryform = category_form_class(content_type,
                                           request.POST,
                                           initial=initial_category_form_data,
                                           prefix='category')

        formset = OfficerFormSet(request.POST,
                                 instance=study_group,
                                 prefix="officers")

        if form.is_valid() and metaform.is_valid() and categoryform.is_valid(
        ) and formset.is_valid():
            study_group = form.save(commit=False)
            # update all permissions and save the model
            study_group = update_perms_and_save(request, form, study_group)

            #save meta
            meta = metaform.save()
            study_group.meta = meta

            formset.save()

            ## update the category of the studygroup
            category_removed = False
            category = categoryform.cleaned_data['category']
            if category != '0':
                Category.objects.update(study_group, category, 'category')
            else:  # remove
                category_removed = True
                Category.objects.remove(study_group, 'category')
                Category.objects.remove(study_group, 'sub_category')

            if not category_removed:
                # update the sub category of the studygroup
                sub_category = categoryform.cleaned_data['sub_category']
                if sub_category != '0':
                    Category.objects.update(study_group, sub_category,
                                            'sub_category')
                else:  # remove
                    Category.objects.remove(study_group, 'sub_category')

            #save relationships
            study_group.save()

            EventLog.objects.log(instance=study_group)

            messages.add_message(request, messages.SUCCESS,
                                 'Successfully updated %s' % study_group)

            if not request.user.profile.is_superuser:
                # send notification to administrators
                recipients = get_notice_recipients('module', 'studygroups',
                                                   'studygrouprecipients')
                if recipients:
                    if notification:
                        extra_context = {
                            'object': study_group,
                            'request': request,
                        }
                        notification.send_emails(recipients,
                                                 'study_group_edited',
                                                 extra_context)

            return HttpResponseRedirect(
                reverse('studygroups.detail', args=[study_group.slug]))
    else:
        form = form_class(instance=study_group, user=request.user)
        metaform = meta_form_class(instance=study_group.meta, prefix='meta')
        categoryform = category_form_class(content_type,
                                           initial=initial_category_form_data,
                                           prefix='category')
        formset = OfficerFormSet(instance=study_group, prefix="officers")
        #formset.form = staticmethod(curry(OfficerForm, study_group_group=study_group.group))

    return render_to_resp(request=request,
                          template_name=template_name,
                          context={
                              'study_group': study_group,
                              'form': form,
                              'metaform': metaform,
                              'categoryform': categoryform,
                              'formset': formset,
                          })