Example #1
1
 def callback(self):
     if self._callback is not None:
         return self._callback
     elif self._callback_str is None:
         return lambda *args, **kwargs: None
     try:
         self._callback = get_callable(self._callback_str)
     except ImportError as e:
         mod_name, _ = get_mod_func(self._callback_str)
         raise ImproperlyConfigured("Could not import '%s'. " "Error was: %s" % (mod_name, str(e)))
     except AttributeError as e:
         mod_name, func_name = get_mod_func(self._callback_str)
         raise ImproperlyConfigured("Tried '%s' in module '%s'. " "Error was: %s" % (func_name, mod_name, str(e)))
     return self._callback
Example #2
0
def get_callable(lookup_view, can_fail=False):
    """
    Convert a string version of a function name to the callable object.

    If the lookup_view is not an import path, it is assumed to be a URL pattern
    label and the original string is returned.

    If can_fail is True, lookup_view might be a URL pattern label, so errors
    during the import fail and the string is returned.
    """
    if not callable(lookup_view):
        mod_name, func_name = get_mod_func(lookup_view)
        try:
            if func_name != "":
                lookup_view = getattr(import_module(mod_name), func_name)
                if not callable(lookup_view):
                    raise ImproperlyConfigured("Could not import %s.%s." % (mod_name, func_name))
        except AttributeError:
            if not can_fail:
                raise ImproperlyConfigured(
                    "Could not import %s. Callable " "does not exist in module %s." % (lookup_view, mod_name)
                )
        except ImportError:
            parentmod, submod = get_mod_func(mod_name)
            if not can_fail and submod != "" and not module_has_submodule(import_module(parentmod), submod):
                raise ImproperlyConfigured(
                    "Could not import %s. Parent " "module %s does not exist." % (lookup_view, mod_name)
                )
            if not can_fail:
                raise
    return lookup_view
Example #3
0
def get_callable(lookup_view, can_fail=False):
    """
    Convert a string version of a function name to the callable object.

    If the lookup_view is not an import path, it is assumed to be a URL pattern
    label and the original string is returned.

    If can_fail is True, lookup_view might be a URL pattern label, so errors
    during the import fail and the string is returned.
    """
    if not callable(lookup_view):
        mod_name, func_name = get_mod_func(lookup_view)
        try:
            if func_name != '':
                lookup_view = getattr(import_module(mod_name), func_name)
                if not callable(lookup_view):
                    raise ImproperlyConfigured("Could not import %s.%s." %
                                               (mod_name, func_name))
        except AttributeError:
            if not can_fail:
                raise ImproperlyConfigured("Could not import %s. Callable "
                                           "does not exist in module %s." %
                                           (lookup_view, mod_name))
        except ImportError:
            parentmod, submod = get_mod_func(mod_name)
            if (not can_fail and submod != '' and not module_has_submodule(
                    import_module(parentmod), submod)):
                raise ImproperlyConfigured("Could not import %s. Parent "
                                           "module %s does not exist." %
                                           (lookup_view, mod_name))
            if not can_fail:
                raise
    return lookup_view
Example #4
0
def get_connected():
    if not settings.PAGE_CONNECTED_MODELS:
        return []

    models = []
    for capp in settings.PAGE_CONNECTED_MODELS:
        model = {}
        mod_name, model_name = get_mod_func(capp['model'])
        model['model_name'] = model_name
        m = getattr(__import__(mod_name, {}, {}, ['']), model_name)
        model['model'] = m

        options = capp.get('options', {})
        model['options'] = options

        if 'form' in capp:
            mod_name, form_name = get_mod_func(capp['form'])
            f = getattr(__import__(mod_name, {}, {}, ['']), form_name)
            model['options'].update({'form': f})

        admin_class = admin.StackedInline
        if 'admin' in capp:
            mod_name, admin_class_name = get_mod_func(capp['admin'])
            admin_class = getattr(__import__(mod_name, {}, {}, ['']),
                                  admin_class_name)

        models.append((admin_class, m, options))

    return models
Example #5
0
def get_connected():
    if not settings.PAGE_CONNECTED_MODELS:
        return []

    models = []
    for capp in settings.PAGE_CONNECTED_MODELS:
        model = {}
        mod_name, model_name = get_mod_func(capp['model'])
        model['model_name'] = model_name
        m = getattr(__import__(mod_name, {}, {}, ['']), model_name)
        model['model'] = m

        options = capp.get('options', {})
        model['options'] = options

        if 'form' in capp:
            mod_name, form_name = get_mod_func(capp['form'])
            f = getattr(__import__(mod_name, {}, {}, ['']), form_name)
            model['options'].update({'form': f})
            
        admin_class = admin.StackedInline
        if 'admin' in capp:
            mod_name, admin_class_name = get_mod_func(capp['admin'])
            admin_class = getattr(__import__(mod_name, {}, {}, ['']), admin_class_name)

        models.append((admin_class, m, options))

    return models
Example #6
0
 def process_step(self, request, form, step):
     super(ModeWizard, self).process_step(request, form, step)
     form0 = self.get_form(0, request.POST)
     if not form0.is_valid():
         return self.render_revalidation_failure(request, 0, form0)
     if not step:
         paths = []
         for i in range(self.num_conditions):
             values = form.cleaned_data['condition_' +
                                        str(i + 1)].split('|')
             if not values[0]:
                 continue
             condition_model, condition_field = get_mod_func(values[0])
             condition_model = globals()[condition_model]
             paths.append(
                 (i + 1, condition_model,
                  path_v1(self.base_model,
                          condition_model), condition_field, values[1]))
         self.form_list[step + 1] = pathchoiceform_factory(
             self.base_model, paths)
     elif step == 2:
         paths = []
         for i in range(self.num_columns):
             values = form.cleaned_data['column_' + str(i + 1)].split('|')
             if not values[0]:
                 continue
             field_model, field_field = get_mod_func(values[0])
             field_model = globals()[field_model]
             paths.append((i + 1, field_model,
                           path_v1(self.base_model,
                                   field_model), field_field, values[1]))
         self.form_list[step + 1] = pathchoiceform_factory(
             self.base_model, paths)
Example #7
0
def get_connected():
    if not settings.PAGE_CONNECTED_MODELS:
        return []

    models = []
    for capp in settings.PAGE_CONNECTED_MODELS:
        model = {}
        mod_name, model_name = get_mod_func(capp["model"])
        model["model_name"] = model_name
        m = getattr(__import__(mod_name, {}, {}, [""]), model_name)
        model["model"] = m

        options = capp.get("options", {})
        model["options"] = options

        if "form" in capp:
            mod_name, form_name = get_mod_func(capp["form"])
            f = getattr(__import__(mod_name, {}, {}, [""]), form_name)
            model["options"].update({"form": f})

        admin_class = admin.StackedInline
        if "admin" in capp:
            mod_name, admin_class_name = get_mod_func(capp["admin"])
            admin_class = getattr(__import__(mod_name, {}, {}, [""]), admin_class_name)

        models.append((admin_class, m, options))

    return models
Example #8
0
    def __new__(cls, prefix=None):
        obj = object.__new__(cls)
        obj.pluggable_unique_identifier = '/@@pluggableapp@@/%s/' % str(uuid.uuid4())
        obj.pluggable_prefix = prefix
        view_prefix = cls.urlpatterns[0]
        urlpatterns = []
        for pattern_type, pattern_args, pattern_kwargs in copy.deepcopy(cls.urlpatterns[1:]):
            if pattern_type == 'url':
                view = pattern_args[1]
                if type(view) == list:
                    raise Exception("Pluggable applications do not support 'include(...)' url definitions.")

                # Handle a view directly
                if callable(view):
                    pattern_args[1] = pluggable_view(view, obj)
                # Handle a view_prefix combined with function name or a full view path
                elif isinstance(view, (str, unicode)) and (view_prefix or '.' in view):
                    view_name = view_prefix and '%s.%s' % (view_prefix, view) or view
                    try:
                        pattern_args[1] = pluggable_view(get_callable(view), obj)
                    except ImportError, e:
                        mod_name, _ = get_mod_func(view)
                        raise ViewDoesNotExist("Could not import %s. Error was: %s" % (mod_name, str(e)))
                    except AttributeError, e:
                        mod_name, func_name = get_mod_func(view)
                        raise ViewDoesNotExist("Tried %s in module %s. Error was: %s" % (func_name, mod_name, str(e)))
                # Handle class view.
                elif isinstance(view, (str, unicode)) and hasattr(obj, view):
                    # Avoid reapplying pluggable view decorator when it has aready been applied. (i.e. the same function is reused in the same configuration.
                    if not getattr(getattr(obj, view), 'pluggable_unique_identifier', '') == obj.pluggable_unique_identifier:
                        setattr(obj, view, pluggable_class_view(getattr(obj, view), obj))
                    pattern_args[1] = getattr(obj, view)
 def render(self, context):
     view = self.view.resolve(context)
     if not callable(view):
         try:
             view = get_callable(view)
         except ImportError, e:
             mod_name, _ = get_mod_func(view)
             raise ViewDoesNotExist(
                 "Could not import %s. Error was: %s" % (mod_name, str(e)))
         except AttributeError, e:
             mod_name, func_name = get_mod_func(view)
             raise ViewDoesNotExist("Tried %s in module %s. Error was: %s" %
                                    (func_name, mod_name, str(e)))
	def search(self, request, collection, filter_parameters, order_parameters):
		
		parameters = ' | '.join(collection.parameters.split(',')).strip(' |')

		objects = SearchQuerySet().filter(content=parameters)
		if hasattr(settings, "COLLECTIONS_HAYSTACK_MODELS"):
			haystack_models = settings.COLLECTIONS_HAYSTACK_MODELS
			
			#if we're a string pull out the function
			if isinstance(haystack_models, str):
				mod_name, func_name = get_mod_func(haystack_models)
				haystack_models = getattr(import_module(mod_name), func_name)

            #if we're a function pull out the models
			if callable(haystack_models):
				haystack_models = haystack_models(request)
            
			model_list = []
			for haystack_model in haystack_models:
				app_model = haystack_model.split('.')
				model_list.append(get_model(*app_model))
			objects.models(*model_list)
		
		if isinstance(order_parameters, list):
			objects = objects.order_by(*order_parameters)
			
		if isinstance(filter_parameters, dict):
			objects = objects.filter(**filter_parameters)
			
		return objects
Example #11
0
def view_detail(request, view):
    if not utils.docutils_is_available:
        return missing_docutils_page(request)

    mod, func = urlresolvers.get_mod_func(view)
    try:
        view_func = getattr(import_module(mod), func)
    except (ImportError, AttributeError):
        raise Http404
    title, body, metadata = utils.parse_docstring(view_func.__doc__)
    if title:
        title = utils.parse_rst(title, 'view', _('view:') + view)
    if body:
        body = utils.parse_rst(body, 'view', _('view:') + view)
    for key in metadata:
        metadata[key] = utils.parse_rst(
            metadata[key], 
            'model', _('view:') + view
        )
    
    name = view.split('.')[-1].replace('_', '/')
    param = {
        'root_path': get_root_path(), 
        'name': name, 
        'summary': title,
        'body': body, 
        'meta': metadata
    }
    
    return render_to_response(
        'doc/view_detail.tpl', 
        param,
        context_instance=RequestContext(request)
    )
Example #12
0
 def validate_view_path_exists(self, lookup_view):
     from django.core import urlresolvers
     try:
         lookup_view = lookup_view.encode('ascii')
         mod_name, func_name = urlresolvers.get_mod_func(lookup_view)
         lookup_view = getattr(urlresolvers.import_module(mod_name), func_name)
         if not callable(lookup_view):
             raise forms.ValidationError("'%s.%s' is not a callable." % (mod_name, func_name))
     except ImportError as e:
         mod_name, _ = urlresolvers.get_mod_func(lookup_view)
         raise forms.ValidationError("Could not import %s. Error was: %s" % (mod_name, str(e)))
     except AttributeError as e:
         mod_name, func_name = urlresolvers.get_mod_func(lookup_view)
         raise forms.ValidationError("Tried %s in module %s. Error was: %s" % (func_name, mod_name, str(e)))
     except Exception as e:
         raise forms.ValidationError("Invalid lookup_view %s. Error was: %s" % (lookup_view, str(e)))
Example #13
0
 def _get_admin_urlconf(self):
     if not hasattr(self, "_admin_urlconf_module"):
         try:
             name = "%s.%s" % (get_mod_func(self.__class__.__module__)[0], "admin_urls")
             self._admin_urlconf_module = __import__(name, {}, {}, [""])
         except Exception, e:
             raise ImproperlyConfigured, "Error while importing extension's admin URLconf %r: %s" % (name, e)
Example #14
0
def callback(request):
    enc_response = request.REQUEST["encResponse"]
    if not enc_response:
        raise d.Http404("No encResponse")

    data = dec_response(request, enc_response)

    if not data:
        raise Http404("Checksum Failed")

    order_id = request.session["dcavenue_order_id"]

    if order_id:
        del request.session["dcavenue_order_id"]
    else:
        raise Http404("No order id in session")

    if order_id != data["Order_Id"]:
        raise Http404("Invalid orderid")

    cb_module, cb_method = get_mod_func(
        settings.DCAVENUE.get("CALLBACK", "dcavenue.utils.default_callback"))
    cb = getattr(__import__(cb_module, {}, {}, ['']), cb_method)

    return cb(request, data)
Example #15
0
def view_detail(request, view):
    if not utils.docutils_is_available:
        return missing_docutils_page(request)

    mod, func = urlresolvers.get_mod_func(view)
    try:
        view_func = getattr(__import__(mod, {}, {}, ['']), func)
    except (ImportError, AttributeError):
        raise Http404
    title, body, metadata = utils.parse_docstring(view_func.__doc__)
    if title:
        title = utils.parse_rst(title, 'view', _('view:') + view)
    if body:
        body = utils.parse_rst(body, 'view', _('view:') + view)
    for key in metadata:
        metadata[key] = utils.parse_rst(metadata[key], 'model',
                                        _('view:') + view)
    return render_to_response('admin_doc/view_detail.html', {
        'root_path': get_root_path(),
        'name': view,
        'summary': title,
        'body': body,
        'meta': metadata,
    },
                              context_instance=RequestContext(request))
Example #16
0
def verify_anon( request, forward_to, *arguments, **keywords):
    """
    verify the captcha and then forward the request  for anonymous users only
    TBD: redirect to the original form with a validation error
    """

    captcha_error = []

    if request.POST and request.user.is_authenticated():
        id = request.POST["captcha_id"]
        word = request.POST["captcha_word"]
        test = _getFactory(SITE_ID).get(id)
        if not test:
            captcha_error.append('Invalid captcha id.')
        if not test.valid:
            captcha_error.append('Test invalidated, try again.')
        elif not test.testSolutions([word]):
            captcha_error.append('Invalid word.')

    mod_name, func_name = urlresolvers.get_mod_func(forward_to)

    try:
        func, ignore = getattr(__import__(mod_name, '', '', ['']), func_name), {}
        return func( request, captcha_error, *arguments, **keywords) 

    except (ImportError, AttributeError), e:
        raise ViewDoesNotExist, "Tried %s. Error was: %s" % (forward_to, str(e))
Example #17
0
    def _lookup_exclude(cls, name):
        '''
        Used to process each object named in BLUESTEM_EXCLUDE setting.
        Attempts first to find as module ...
        '''

        #   Try importing name as module.
        try:
            mod = import_module(name)

        #   If name doesn't import as module, we go on to determine whether
        #   name is instead a view reference.
        except ImportError:
            pass

        #   Raise exception if something else is amiss with import.
        except ValueError:
            raise ImproperlyConfigured \
                    ('Error processing BLUESTEM_EXCLUDE. Is BLUESTEM_EXCLUDE '
                     'a correctly defined list or tuple?')

        #   Module import succeeded.
        else:
            #   If urlpatterns attribute isn't present; name isn't a proper
            #   url module reference.
            if not hasattr(mod, 'urlpatterns'):
                raise ImproperlyConfigured \
                        ('Module \'%s\' lacks a \'urlpatterns\' attribute' % \
                         mod.__name__)

            #   Return list of callback functions for every item in urlpatterns.
            return [ u.callback for u in mod.urlpatterns if u.callback ]

        #   Since name didn't import as module, we now see whether it's
        #   a reference to a view function contained in a module.
        mod_name, func_name = get_mod_func(name)

        #   Try importing containing module.
        try:
            mod = import_module(mod_name)
                
        #   Raise exception if module doesn't import.
        except ImportError:
            raise ImproperlyConfigured \
                    ('Name \'%s\' is neither url module or view' % name)

        #   Determine if named function is an attribute in module.
        try:
            view_func = getattr(mod, func_name)

        #   Not found; raise an exception.
        except AttributeError:
            raise ImproperlyConfigured \
                    ('Module \'%s\' does not define a \'%s\' view' % \
                     (mod_name, func_name))

        #   Return callback function for view. (Returned as list to be
        #   consistent with behavior when processing a name that's url module.)
        return [ view_func ]
Example #18
0
 def callback(self):
     if self._callback is not None:
         return self._callback
     elif self._callback_str is None:
         return lambda *args, **kwargs: None
     try:
         self._callback = get_callable(self._callback_str)
     except ImportError as exc:
         mod_name, _ = get_mod_func(self._callback_str)
         raise ImproperlyConfigured("Could not import '%s'. "
                                    "Error was: %s" % (mod_name, str(exc)))
     except AttributeError as exc:
         mod_name, func_name = get_mod_func(self._callback_str)
         raise ImproperlyConfigured("Tried importing '%s' from module "
                                    "'%s' but failed. Error was: %s" %
                                    (func_name, mod_name, str(exc)))
     return self._callback
Example #19
0
    def __new__(cls, prefix=None):
        obj = object.__new__(cls)
        obj.pluggable_unique_identifier = '/@@pluggableapp@@/%s/' % str(
            uuid.uuid4())
        obj.pluggable_prefix = prefix
        view_prefix = cls.urlpatterns[0]
        urlpatterns = []
        for pattern_type, pattern_args, pattern_kwargs in copy.deepcopy(
                cls.urlpatterns[1:]):
            if pattern_type == 'url':
                view = pattern_args[1]
                if type(view) == list:
                    raise Exception(
                        "Pluggable applications do not support 'include(...)' url definitions."
                    )

                # Handle a view directly
                if callable(view):
                    pattern_args[1] = pluggable_view(view, obj)
                # Handle a view_prefix combined with function name or a full view path
                elif isinstance(view, (str, unicode)) and (view_prefix
                                                           or '.' in view):
                    view_name = view_prefix and '%s.%s' % (view_prefix,
                                                           view) or view
                    try:
                        pattern_args[1] = pluggable_view(
                            get_callable(view), obj)
                    except ImportError, e:
                        mod_name, _ = get_mod_func(view)
                        raise ViewDoesNotExist(
                            "Could not import %s. Error was: %s" %
                            (mod_name, str(e)))
                    except AttributeError, e:
                        mod_name, func_name = get_mod_func(view)
                        raise ViewDoesNotExist(
                            "Tried %s in module %s. Error was: %s" %
                            (func_name, mod_name, str(e)))
                # Handle class view.
                elif isinstance(view, (str, unicode)) and hasattr(obj, view):
                    # Avoid reapplying pluggable view decorator when it has aready been applied. (i.e. the same function is reused in the same configuration.
                    if not getattr(getattr(
                            obj, view), 'pluggable_unique_identifier',
                                   '') == obj.pluggable_unique_identifier:
                        setattr(obj, view,
                                pluggable_class_view(getattr(obj, view), obj))
                    pattern_args[1] = getattr(obj, view)
Example #20
0
 def _get_parameters_from_setting(self, var_name, request):
     "Get the parameters from the function specified in the settings"
     if hasattr(settings, var_name):
         request_cleaner = getattr(settings, var_name)
         if not callable(request_cleaner):
             mod_name, func_name = get_mod_func(request_cleaner)
             request_cleaner = getattr(import_module(mod_name), func_name)
             return request_cleaner(request)
     return None
Example #21
0
def validate_generic(request,formclass):
	mod_name, form_name = get_mod_func(formclass)
	formclass = getattr(__import__(mod_name, {}, {}, ['']), form_name)
	form = formclass(request.POST)
	if(request.GET.has_key('field')):
		errors = form.errors.get(request.GET['field'],[])
	else:
		errors = form.errors
	return JsonResponse({'valid': not errors, 'errors': errors})
Example #22
0
 def admin_urlconf(self):
     """The module defining URLs for the extension's admin site."""
     try:
         name = '%s.%s' % (get_mod_func(self.__class__.__module__)[0],
                           'admin_urls')
         return __import__(name, {}, {}, [''])
     except Exception as e:
         raise ImproperlyConfigured(
             "Error while importing extension's admin URLconf %r: %s" %
             (name, e))
Example #23
0
 def _get_admin_urlconf(self):
     if not hasattr(self, "_admin_urlconf_module"):
         try:
             name = "%s.%s" % (get_mod_func(
                 self.__class__.__module__)[0], "admin_urls")
             self._admin_urlconf_module = __import__(name, {}, {}, [''])
         except Exception, e:
             raise ImproperlyConfigured, \
                 "Error while importing extension's admin URLconf %r: %s" % \
                 (name, e)
Example #24
0
 def admin_urlconf(self):
     """The module defining URLs for the extension's admin site."""
     try:
         name = '%s.%s' % (get_mod_func(
             self.__class__.__module__)[0], 'admin_urls')
         return __import__(name, {}, {}, [''])
     except Exception as e:
         raise ImproperlyConfigured(
             "Error while importing extension's admin URLconf %r: %s" %
             (name, e))
Example #25
0
def test_handler_500():
    settings.DEBUG = False
    mod_name, func_name = get_mod_func(handler500)
    callback = getattr(import_module(mod_name), func_name), {}
    response = callback[0](get_request_fixture())

    content = response.content

    assert isinstance(response, HttpResponseServerError)
    assert '<h1>500</h1>' in content
Example #26
0
def get_module_attribute(path):
    """
    Convert a string version of a function name to the callable object.
    """
    lookup_callable = None
    mod_name, attr = get_mod_func(path)
    mod = import_module(mod_name)
    if attr != '':
        lookup_callable = getattr(mod, attr)
    return lookup_callable
Example #27
0
 def callback(self):
     if self._callback is not None:
         return self._callback
     elif self._callback_str is None:
         return lambda *args, **kwargs: None
     try:
         self._callback = get_callable(self._callback_str)
     except ImportError, e:
         mod_name, _ = get_mod_func(self._callback_str)
         raise ImproperlyConfigured(
             "Could not import '%s'. Error was: %s" % (mod_name, str(e)))
def get_view(lookup_view):
    """
    Uses similar logic to django.urlresolvers.get_callable, but always raises
    on failures and supports class based views.
    """
    lookup_view = lookup_view.encode('ascii')
    mod_name, func_or_class_name = get_mod_func(lookup_view)
    assert func_or_class_name != ''
    view = getattr(import_module(mod_name), func_or_class_name)
    assert callable(view) or hasattr(view, 'as_view')
    return view
Example #29
0
def get_view(lookup_view):
    """
    Uses similar logic to django.urlresolvers.get_callable, but always raises
    on failures and supports class based views.
    """
    lookup_view = lookup_view.encode('ascii')
    mod_name, func_or_class_name = get_mod_func(lookup_view)
    assert func_or_class_name != ''
    view = getattr(import_module(mod_name), func_or_class_name)
    assert callable(view) or hasattr(view, 'as_view')
    return view
Example #30
0
 def validate_view_path_exists(self, lookup_view):
     from django.core import urlresolvers
     try:
         lookup_view = lookup_view.encode('ascii')
         mod_name, func_name = urlresolvers.get_mod_func(lookup_view)
         lookup_view = getattr(urlresolvers.import_module(mod_name),
                               func_name)
         if not callable(lookup_view):
             raise forms.ValidationError("'%s.%s' is not a callable." %
                                         (mod_name, func_name))
     except ImportError as e:
         mod_name, _ = urlresolvers.get_mod_func(lookup_view)
         raise forms.ValidationError("Could not import %s. Error was: %s" %
                                     (mod_name, str(e)))
     except AttributeError as e:
         mod_name, func_name = urlresolvers.get_mod_func(lookup_view)
         raise forms.ValidationError(
             "Tried %s in module %s. Error was: %s" %
             (func_name, mod_name, str(e)))
     except Exception as e:
         raise forms.ValidationError(
             "Invalid lookup_view %s. Error was: %s" %
             (lookup_view, str(e)))
Example #31
0
def from_dotted_path(fullpath):
    """
    Returns the specified attribute of a module, specified by a string.

    ``from_dotted_path('a.b.c.d')`` is roughly equivalent to::

        from a.b.c import d

    except that ``d`` is returned and not entered into the current namespace.
    """

    module_name, fn_name = get_mod_func(fullpath)

    return getattr(importlib.import_module(module_name), fn_name)
Example #32
0
def ajax_form_handler(
    request, form_cls, require_login=True, allow_get=settings.DEBUG
):
    if require_login and not request.user.is_authenticated(): 
        raise Http404("login required")
    if not allow_get and request.method != "POST":
        raise Http404("only post allowed")
    if isinstance(form_cls, basestring):
        # can take form_cls of the form: "project.app.forms.FormName"
        from django.core.urlresolvers import get_mod_func
        mod_name, form_name = get_mod_func(form_cls)
        form_cls = getattr(__import__(mod_name, {}, {}, ['']), form_name)
    form = form_cls(request, request.REQUEST)
    if form.is_valid():
        return JSONResponse({ 'success': True, 'response': form.save() })
    return JSONResponse({ 'success': False, 'errors': form.errors })
Example #33
0
 def get_context_data(self, **kwargs):
     view = self.kwargs["view"]
     urlconf = urlresolvers.get_urlconf()
     if urlresolvers.get_resolver(urlconf)._is_callback(view):
         mod, func = urlresolvers.get_mod_func(view)
         view_func = getattr(import_module(mod), func)
     else:
         raise Http404
     title, body, metadata = utils.parse_docstring(view_func.__doc__)
     if title:
         title = utils.parse_rst(title, "view", _("view:") + view)
     if body:
         body = utils.parse_rst(body, "view", _("view:") + view)
     for key in metadata:
         metadata[key] = utils.parse_rst(metadata[key], "model", _("view:") + view)
     kwargs.update({"name": view, "summary": title, "body": body, "meta": metadata})
     return super(ViewDetailView, self).get_context_data(**kwargs)
Example #34
0
def handle_tiny_url(request, tiny_id):
    tiny_url = get_object_or_404(TinyURL, tiny_id=tiny_id)
    if tiny_url.action == "r":
        return HttpResponseRedirect(tiny_url.data)
    elif tiny_url.action == "m":
        return tiny_url.content_object.render(request)
    elif tiny_url.action == "v":
        mod_name, view_name = get_mod_func(tiny_url.data)
        view = getattr(__import__(mod_name, {}, {}, ['']), view_name)
        return view(request, tiny_url.content_object)
    elif tiny_url.action == "i":
        return render_to_response(
            "dtinyurl/inline.html", { 'tiny_url': tiny_url },
            context_instance = RequestContext(request)
        )
    else:
        raise AssertionError("bad action: %s" % tiny_url.action)
Example #35
0
def ajax_validator(request, form_cls):
    """
    Usage
    -----

    # in urls.py have something like this:
    urlpatterns = patterns('',
        # ... other patterns
        (
            r'^ajax/validate-registration-form/$', 'ajax_validator',
            { 'form_cls': 'myproject.accounts.forms.RegistrationForm' }
        ),
    )

    # sample javascript code to use the validator
    $(function(){
        $("#id_username, #id_password, #id_password2, #id_email").blur(function(){
            var url = "/ajax/validate-registration-form/?field=" + this.name;
            var field = this.name;
            $.ajax({
                url: url, data: $("#registration_form").serialize(),
                type: "post", dataType: "json",    
                success: function (response){ 
                    if(response.valid)
                    {
                        $("#"+field+"_errors").html("Sounds good");
                    }
                    else
                    {
                        $("#"+field+"_errors").html(response.errors);
                    }
                }
            });
        });
    });
    """
    mod_name, form_name = get_mod_func(form_cls)
    form_cls = getattr(__import__(mod_name, {}, {}, ['']), form_name)
    form = form_cls(request.POST)
    if "field" in request.GET:
        errors = form.errors.get(request.GET["field"])
        if errors: errors = errors.as_text()
    else:
        errors = form.errors
    return JSONResponse({ "errors": errors, "valid": not errors })
Example #36
0
def tool(request, model_cls, form_cls, template, ctx=DEFAULT_CONTEXT, next="", **kwargs):
    
    # Allow passing model_cls as a string.
    if isinstance(model_cls, str):
        mod_name, model_name = get_mod_func(model_cls)
        model_cls = getattr(__import__(mod_name, {}, {}, ['']), model_name)
    
    #TODO: Could allow this to be overridden easier?
    class ToolForm(form_cls):
        objs = forms.ModelMultipleChoiceField(model_cls._default_manager.all())
    
    form = ToolForm(request.POST or None)
    if form.is_valid():
        form.save(request, **kwargs)
        return HttpResponseRedirect(next)
    
    ctx['form'] = form
    return render_to_response(template, ctx , RequestContext(request))
Example #37
0
    def _get_clients(self):
        """
        Return a list of (protocol-name, display-name, client-object) tuples
        for all installed backlinks modules.

        """
        if not self._clients:
            self._clients = []
            for name, display, client_name in settings.INSTALLED_MODULES:
                try:
                    module_name, obj = get_mod_func(client_name)
                    mod = __import__(module_name)
                    client_module = sys.modules[module_name]
                    client = getattr(client_module, obj)
                except (ImportError, AttributeError):
                    continue
                if hasattr(client, 'autodiscover'):
                    self._clients.append((name, display, client))
        return self._clients
Example #38
0
    def _get_clients(self):
        """
        Return a list of (protocol-name, display-name, client-object) tuples
        for all installed backlinks modules.

        """
        if not self._clients:
            self._clients = []
            for name, display, client_name in settings.INSTALLED_MODULES:
                try:
                    module_name, obj = get_mod_func(client_name)
                    mod = __import__(module_name)
                    client_module = sys.modules[module_name]
                    client = getattr(client_module, obj)
                except (ImportError, AttributeError):
                    continue
                if hasattr(client, 'autodiscover'):
                    self._clients.append((name, display, client))
        return self._clients
Example #39
0
 def get_context_data(self, **kwargs):
     view = self.kwargs['view']
     mod, func = urlresolvers.get_mod_func(view)
     try:
         view_func = getattr(import_module(mod), func)
     except (ImportError, AttributeError):
         raise Http404
     title, body, metadata = utils.parse_docstring(view_func.__doc__)
     if title:
         title = utils.parse_rst(title, 'view', _('view:') + view)
     if body:
         body = utils.parse_rst(body, 'view', _('view:') + view)
     for key in metadata:
         metadata[key] = utils.parse_rst(metadata[key], 'model', _('view:') + view)
     kwargs.update({
         'name': view,
         'summary': title,
         'body': body,
         'meta': metadata,
     })
     return super(ViewDetailView, self).get_context_data(**kwargs)
Example #40
0
def view_detail(request, view):
    if not utils.docutils_is_available:
        return missing_docutils_page(request)

    mod, func = urlresolvers.get_mod_func(view)
    try:
        view_func = getattr(import_module(mod), func)
    except (ImportError, AttributeError):
        raise Http404
    title, body, metadata = utils.parse_docstring(view_func.__doc__)
    if title:
        title = utils.parse_rst(title, "view", _("view:") + view)
    if body:
        body = utils.parse_rst(body, "view", _("view:") + view)
    for key in metadata:
        metadata[key] = utils.parse_rst(metadata[key], "model", _("view:") + view)

    name = view.split(".")[-1].replace("_", "/")
    param = {"root_path": get_root_path(), "name": name, "summary": title, "body": body, "meta": metadata}

    return render_to_response("doc/view_detail.tpl", param, context_instance=RequestContext(request))
Example #41
0
 def get_context_data(self, **kwargs):
     view = self.kwargs['view']
     mod, func = urlresolvers.get_mod_func(view)
     try:
         view_func = getattr(import_module(mod), func)
     except (ImportError, AttributeError):
         raise Http404
     title, body, metadata = utils.parse_docstring(view_func.__doc__)
     if title:
         title = utils.parse_rst(title, 'view', _('view:') + view)
     if body:
         body = utils.parse_rst(body, 'view', _('view:') + view)
     for key in metadata:
         metadata[key] = utils.parse_rst(metadata[key], 'model',
                                         _('view:') + view)
     kwargs.update({
         'name': view,
         'summary': title,
         'body': body,
         'meta': metadata,
     })
     return super(ViewDetailView, self).get_context_data(**kwargs)
Example #42
0
def view_detail(request, view):
    if not utils.docutils_is_available:
        return missing_docutils_page(request)

    mod, func = urlresolvers.get_mod_func(view)
    try:
        view_func = getattr(__import__(mod, {}, {}, ['']), func)
    except (ImportError, AttributeError):
        raise Http404
    title, body, metadata = utils.parse_docstring(view_func.__doc__)
    if title:
        title = utils.parse_rst(title, 'view', _('view:') + view)
    if body:
        body = utils.parse_rst(body, 'view', _('view:') + view)
    for key in metadata:
        metadata[key] = utils.parse_rst(metadata[key], 'model', _('view:') + view)
    return render_to_response('admin_doc/view_detail.html', {
        'name': view,
        'summary': title,
        'body': body,
        'meta': metadata,
    }, context_instance=RequestContext(request))
Example #43
0
 def get_context_data(self, **kwargs):
     view = self.kwargs['view']
     urlconf = urlresolvers.get_urlconf()
     if urlresolvers.get_resolver(urlconf)._is_callback(view):
         mod, func = urlresolvers.get_mod_func(view)
         view_func = getattr(import_module(mod), func)
     else:
         raise Http404
     title, body, metadata = utils.parse_docstring(view_func.__doc__)
     if title:
         title = utils.parse_rst(title, 'view', _('view:') + view)
     if body:
         body = utils.parse_rst(body, 'view', _('view:') + view)
     for key in metadata:
         metadata[key] = utils.parse_rst(metadata[key], 'model', _('view:') + view)
     kwargs.update({
         'name': view,
         'summary': title,
         'body': body,
         'meta': metadata,
     })
     return super(ViewDetailView, self).get_context_data(**kwargs)
Example #44
0
    def render(self, rerender):
        # Add some classes to the block to help style it
        block_classes = self.css_classes()

        block_class = self.content_block.content_type.model_class()
        render_function = block_class.render_function
        mod_name, func_name = get_mod_func(render_function)
        block_view = getattr(import_module(mod_name), func_name)

        if self.block:
            # Following https://github.com/blancltd/django-glitter/pull/15, now when adding a
            # `GlitterBlock` to a page, `self.block` will not be set until the GlitterBlock has
            # been saved on the front end.
            #
            # There's Block Views around, e.g. `glitter.blocks.form.views.form_view`, which
            # presume `self.block` will be set and then error out.
            #
            # Ideally we'd change all the custom view functions to be less error prone, but
            # this is the more defensive approach.
            self.html = block_view(
                self.block, self.glitter_page.request, rerender, self.content_block, block_classes
            )
Example #45
0
def _convert_data(report,result,column_list):
    """
        Apply unicode conversion and data filters to the data in
        result, and return the converted data.
    """
    data_filter_func = None
    if report.data_filter:
        mod_name, func_name = get_mod_func(report.data_filter)
        data_filter_func = getattr(__import__(mod_name, '', '', ['']), func_name)

    display_data=[]
    for row in result:
        display_data_row = []
        i = 0
        for data in row:
            if data_filter_func:
                data = data_filter_func(column_list[i], data)
            if report.data_source.data_encoding == '8859':
                data = unicode(str(data), "iso-8859-1")
            display_data_row.append(data)
            i = i + 1
        display_data.append(display_data_row)
    return display_data
Example #46
0
def form_handler(
    request, form_cls, require_login=False, block_get=False, json=False,
    next=None, template=None, login_url=None, success_template=None,
    validate_only=False, form_renderer=None, **kwargs
):
    next = next or (request.REQUEST.get("next"))
    json = json or (request.REQUEST.get("json") == "true")
    validate_only = validate_only or (request.REQUEST.get("validate_only") == "true")
    login_url = login_url or request.REQUEST.get("login_url") or getattr(settings, "LOGIN_URL", "/accounts/login/")

    if isinstance(form_cls, basestring):
        # can take form_cls of the form: "project.app.forms.FormName"
        mod_name, form_name = get_mod_func(form_cls)
        form_cls = getattr(__import__(mod_name, {}, {}, ['']), form_name)

    # Check Logged in status
    if require_login:
        logged_in = False
        if callable(require_login):
            logged_in = require_login(request)
        else:
            logged_in = request.user.is_authenticated()
        if not logged_in:
            redirect_url = "%s?next=%s" % (login_url, urllib2.quote(request.get_full_path()))
            if json:
                return JSONResponse({ 'success': False, 'redirect': redirect_url })
            else:
                return HttpResponseRedirect(redirect_url)

    #Check block get
    if block_get and request.method != "POST":
        raise Http404("Only Post Allowed")

    # render for a GET request
    if request.method == "GET":
        form = get_form(form_cls, request, with_data=False, **kwargs)
        if template:
            if form.__metaclass__ == forms.models.ModelFormMetaclass and form.instance:
                form.initial = forms.model_to_dict(form.instance, form._meta.fields, form._meta.exclude)
            if json:
                rendered_form = render_to_string(
                    template, {'form':form}, context_instance=RequestContext(request)
                )
                return JSONResponse({'form':rendered_form}) #show we send back the kwargs also?
            else:
                return render_to_response(
                    template, {"form": form}, context_instance=RequestContext(request)
                )
        #if template is not present, it has to be a json call
        else:
            if form_renderer:
                rendered_form = getattr(form, form_renderer)() # form.as_table, form.as_ul etc.
                return JSONResponse({'form':rendered_form}) #show we send back the kwargs also?
            else:
                return JSONResponse(get_form_representation(form))


    #with request method as POST
    form = get_form(form_cls, request, with_data=True, **kwargs)

    #Form validation
    if form.is_valid():
        if validate_only: # return if its only for validation, validate only assumes json=True
            return JSONResponse({"valid": True, "errors": {}})
        resp = form.save()
        if json:
            #The form must return a json serializable dictionary
            return JSONResponse({
                'success': True,
                'response': resp
            })
        else:
            if next: return HttpResponseRedirect(next)
            if isinstance(resp, HttpResponse): return resp
            if success_template or template:
                #get success_template to render after successfull save or use the request GET template
                template_to_render = success_template or template
                return render_to_response(
                    template_to_render, {"form": form, 'saved' : resp}, context_instance=RequestContext(request)
                )

    else:
        errors = form.errors
        if validate_only:
            return JSONResponse({ "errors": errors, "valid": False})
        else:
            if json:
                return JSONResponse({ 'success': False, 'errors': form.errors })
            if template:
                return render_to_response(
                    template, {"form": form}, context_instance=RequestContext(request)
                )
Example #47
0
# DDF_DEFAULT_DATA_FIXTURE default = 'sequential'
# It must be 'sequential', 'static_sequential', 'global_sequential', 'random' or 'path.to.CustomDataFixtureClass'
try:
    INTERNAL_DATA_FIXTURES = {
        'sequential': SequentialDataFixture(),
        'static_sequential': StaticSequentialDataFixture(),
        'global_sequential': GlobalSequentialDataFixture(),
        'random': RandomDataFixture()
    }
    if hasattr(settings, 'DDF_DEFAULT_DATA_FIXTURE'):
        if settings.DDF_DEFAULT_DATA_FIXTURE in INTERNAL_DATA_FIXTURES.keys():
            DDF_DEFAULT_DATA_FIXTURE = INTERNAL_DATA_FIXTURES[
                settings.DDF_DEFAULT_DATA_FIXTURE]
        else:
            # path.to.CustomDataFixtureClass
            mod_name, obj_name = get_mod_func(
                settings.DDF_DEFAULT_DATA_FIXTURE)
            module = import_module(mod_name)
            custom_data_fixture = getattr(module, obj_name)
            DDF_DEFAULT_DATA_FIXTURE = custom_data_fixture()
    else:
        DDF_DEFAULT_DATA_FIXTURE = INTERNAL_DATA_FIXTURES['sequential']
except:
    six.reraise(
        DDFImproperlyConfigured,
        DDFImproperlyConfigured(
            "DDF_DEFAULT_DATA_FIXTURE (%s) must be 'sequential', 'static_sequential', 'global_sequential', 'random' or 'path.to.CustomDataFixtureClass'."
            % settings.DDF_DEFAULT_DATA_FIXTURE),
        sys.exc_info()[2])

# DDF_IGNORE_FIELDS default = []
try:
Example #48
0
                                 False)
RESTRICT_OOTB_AUTH = getattr(settings, 'RPC4DJANGO_RESTRICT_OOTB_AUTH', True)

JSON_ENCODER = getattr(settings, 'RPC4DJANGO_JSON_ENCODER',
                       'django.core.serializers.json.DjangoJSONEncoder')

try:
    # Python2
    basestring
except NameError:
    # Python3
    basestring = str

# resolve JSON_ENCODER to class if it's a string
if isinstance(JSON_ENCODER, basestring):
    mod_name, cls_name = get_mod_func(JSON_ENCODER)
    json_encoder = getattr(import_module(mod_name), cls_name)
else:
    json_encoder = JSON_ENCODER

# instantiate the rpcdispatcher -- this examines the INSTALLED_APPS
# for any @rpcmethod decorators and adds them to the callable methods
dispatcher = RPCDispatcher(RESTRICT_INTROSPECTION, RESTRICT_OOTB_AUTH,
                           json_encoder)


def rpcmethod(**kwargs):
    '''
    Accepts keyword based arguments that describe the method's rpc aspects

    **Parameters**
Example #49
0
    def done(self, request, form_list):
        args = []
        for i in range(self.num_conditions):
            values = form_list[0].cleaned_data['condition_' +
                                               str(i + 1)].split(u'|')
            if not values[0]:
                continue
            condition_model, condition_field = get_mod_func(values[0])
            condition_model = globals()[condition_model]
            query_term = values[1]
            text = values[2]
            val = condition_model._meta.init_name_map(
            )[condition_field][0].to_python(text)
            args.append(
                (condition_model, str(condition_field), str(query_term), val))
        condition_paths = defaultdict(list)
        headers = []
        for field_name, paths in form_list[1].cleaned_data.iteritems():
            condition_model = globals()[get_mod_func(
                field_name.partition('|')[2])[0]]
            for path in paths:
                condition_paths[condition_model].append(
                    path.rpartition(LOOKUP_SEP)[0])
        headers = defaultdict(list)
        view_paths = []
        counts = {}
        for field_name, paths in form_list[3].cleaned_data.iteritems():
            I = int(field_name.partition('|')[0])
            for path in paths:
                if 'Count' in path:
                    path
                    actual_path = path.rpartition(LOOKUP_SEP)[0]
                    path = path.replace(LOOKUP_SEP, u'_')
                    counts[path] = Count(actual_path, distinct=True)
                view_paths.append(path)
                headers[I].append(path)
        if not ('pk' in view_paths or 'id' in view_paths):
            headers[0].append('pk')
        headers = [[
            path, form_list[2].cleaned_data['column_' + str(I)].split(u'|')[1]
            if I else self.base_model.__name__ + u' Primary Key ID#'
        ] for I in range(self.num_columns + 1) for path in headers[I]]
        queryset = path_v5(self.base_model, condition_paths,
                           *args).annotate(**counts)

        fields = [header[0] for header in headers]
        data = {}
        for field in fields:
            data[field] = list(queryset.values_list('pk', field))
        pks = queryset.values_list('pk', flat=True)
        for pk in pks:
            data[pk] = defaultdict(list)
        for field in fields:
            for (pk, datum) in data[field]:
                data[pk][field].append(datum)
        from tempfile import TemporaryFile
        from xlwt import Workbook
        book = Workbook()
        sheet1 = book.add_sheet('Sheet 1')
        field_locations = {}
        for j, header in enumerate(headers):
            sheet1.write(0, j, header[1])
            field_locations[header[0]] = j
        for i, pk in enumerate(pks):
            for field in fields:
                sheet1.write(i + 1, field_locations[field],
                             ', '.join(map(str, data[pk][field])))
        response = HttpResponse(mimetype="application/ms-excel")
        response[
            'Content-Disposition'] = 'attachment; filename=%s' % 'DataViews.xls'
        book.save(response)
        return response
Example #50
0
def _form_handler(request,
                  form_cls,
                  require_login=False,
                  block_get=False,
                  ajax=False,
                  next=None,
                  template=None,
                  login_url=None,
                  pass_request=True,
                  validate_only=False,
                  **kwargs):
    """
    Some ajax heavy apps require a lot of views that are merely a wrapper
    around the form. This generic view can be used for them.
    """
    if "next" in request.REQUEST: next = request.REQUEST["next"]
    from django.shortcuts import render_to_response
    is_ajax = request.is_ajax() or ajax or request.REQUEST.get(
        "json") == "true"
    if isinstance(form_cls, basestring):
        # can take form_cls of the form: "project.app.forms.FormName"
        mod_name, form_name = get_mod_func(form_cls)
        form_cls = getattr(__import__(mod_name, {}, {}, ['']), form_name)
    validate_only = (validate_only
                     or request.REQUEST.get("validate_only") == "true")
    if login_url is None:
        login_url = getattr(settings, "LOGIN_URL", "/login/")
    if callable(require_login):
        require_login = require_login(request)
    elif require_login:
        require_login = not request.user.is_authenticated()
    if require_login:
        redirect_url = "%s?next=%s" % (
            login_url, urlquote(request.get_full_path()))  # FIXME
        if is_ajax:
            return JSONResponse({'success': False, 'redirect': redirect_url})
        return HttpResponseRedirect(redirect_url)
    if block_get and request.method != "POST":
        raise Http404("only post allowed")
    if next: assert template, "template required when next provided"

    def get_form(with_data=False):
        form = form_cls(request) if pass_request else form_cls()
        form.next = next
        if with_data:
            form.data = request.REQUEST
            form.files = request.FILES
            form.is_bound = True
        if hasattr(form, "init"):
            res = form.init(**kwargs)
            if res: raise ResponseReady(res)
        return form

    if is_ajax and request.method == "GET":
        return JSONResponse(get_form_representation(get_form()))
    if template and request.method == "GET":
        return render_to_response(template, {"form": get_form()},
                                  context_instance=RequestContext(request))
    form = get_form(with_data=True)
    if form.is_valid():
        if validate_only:
            return JSONResponse({"valid": True, "errors": {}})
        r = form.save()
        if is_ajax:
            return JSONResponse({
                'success':
                True,
                'response':
                (form.get_json(r) if hasattr(form, "get_json") else r)
            })
        if isinstance(r, HttpResponse): return r
        if next: return HttpResponseRedirect(next)
        if template: return HttpResponseRedirect(r)
        return JSONResponse({
            'success':
            True,
            'response': (form.get_json(r) if hasattr(form, "get_json") else r)
        })
    if validate_only:
        if "field" in request.REQUEST:
            errors = form.errors.get(request.REQUEST["field"], "")
            if errors: errors = "".join(errors)
        else:
            errors = form.errors
        return JSONResponse({"errors": errors, "valid": not errors})
    if is_ajax:
        return JSONResponse({'success': False, 'errors': form.errors})
    if template:
        return render_to_response(template, {"form": form},
                                  context_instance=RequestContext(request))
    return JSONResponse({'success': False, 'errors': form.errors})
Example #51
0
        Decimal(amount) / Decimal(bitcoinprice_eur()['24h']))


def getNewBitcoinPayment_eur(amount):
    return new_bitcoin_payment_eur(amount)


# initialize the conversion module

from django_bitcoin import currency

from django.core import urlresolvers
from django.utils import importlib

for dottedpath in settings.BITCOIN_CURRENCIES:
    mod, func = urlresolvers.get_mod_func(dottedpath)
    klass = getattr(importlib.import_module(mod), func)
    currency.exchange.register_currency(klass())

# Historical prie storage


class HistoricalPrice(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    price = models.DecimalField(max_digits=16, decimal_places=2)
    params = models.CharField(max_length=50)
    currency = models.CharField(max_length=10)

    class Meta:
        verbose_name = _('HistoricalPrice')
        verbose_name_plural = _('HistoricalPrices')
Example #52
0
from django.conf import settings
from django.core.urlresolvers import get_mod_func

REGISTRY = {}

backends = getattr(settings, 'SMSGATEWAY_BACKENDS', ())

for entry in backends:
    module_name, class_name = get_mod_func(entry)
    backend_class = getattr(__import__(module_name, {}, {}, ['']), class_name)
    instance = backend_class()
    REGISTRY[instance.get_slug()] = instance

def get_backend(slug):
    return REGISTRY.get(slug, None)