Ejemplo n.º 1
0
Archivo: ajax.py Proyecto: youen/djity
def add_module(request, js_target, tab_name, module_type, context=None):
    """
    Create a new tabulation in a project
    """
    from django.db.models import Max
    from django.db.models.loading import get_app
    from djity.utils.security import db_table_exists

    tables = [
        module_type.lower() + '_' + module_type.lower(),
        'djity_' + module_type.lower() + '_' + module_type.lower()
    ]
    if not db_table_exists(tables):
        js_target.message(
            _("Tab creation failed. There is no table %s in the database, contact the administrator."
              % module_type))
        return

    try:
        model = get_app(module_type.lower()).__getattribute__(module_type)
    except:
        model = get_app('djity_' +
                        module_type.lower()).__getattribute__(module_type)

    project = context['project']
    i = project.modules.aggregate(Max('tab_position'))['tab_position__max'] + 1
    if module_type == 'SimplePage':
        name = None
    else:
        name = module_type.lower()

    module = model(project=project, name=name, label=tab_name, tab_position=i)
    module.save()

    js_target.redirect(module.djity_url(context))
Ejemplo n.º 2
0
 def yumlfy(self, applications):
     F = YUMLFormatter()
     model_list = []
     arrow_list = []
     external_model = set()
     for app_module in applications:
         models = get_models(app_module)
         if not models:
             continue
         for m in models:
             string = F.label(m) + F.PIPE
             fields = [f for f in m._meta.fields if not f.auto_created]
             for field in fields:
                 string += F.field(field)
                 if field.rel:
                     arrow_list.append(F.relation(m, field.rel))
                     if get_app(field.rel.to._meta.app_label) not in applications:
                         external_model.add(field.rel.to)
             fields = [f for f in m._meta.many_to_many]
             for field in fields:
                 string += F.field(field)
                 if field.rel.through._meta.auto_created:
                     arrow_list.append(F.relation(m, field.rel))
                 else:
                     arrow_list.append(F.through(m, field.rel))
                 if get_app(field.rel.to._meta.app_label) not in applications:
                     external_model.add(field.rel.to)
             model_list.append(F.wrap(string))
             for parent in m._meta.parents:
                 arrow_list.append(F.inherit(m, parent))
                 if get_app(parent._meta.app_label) not in applications:
                     external_model.add(parent)
     for ext in external_model:
         model_list.append(F.external(ext))
     return model_list + arrow_list
Ejemplo n.º 3
0
Archivo: ajax.py Proyecto: albanm/djity
def add_module(request, js_target, tab_name, module_type, context=None):
    """
    Create a new tabulation in a project
    """
    from django.db.models import Max
    from django.db.models.loading import get_app
    from djity.utils.security import db_table_exists

    tables = [module_type.lower()+'_'+module_type.lower(),'djity_'+module_type.lower()+'_'+module_type.lower()]
    if not db_table_exists(tables):
        js_target.message(_("Tab creation failed. There is no table %s in the database, contact the administrator." % module_type))
        return

    try:
        model  = get_app(module_type.lower()).__getattribute__(module_type)
    except:
        model  = get_app('djity_'+module_type.lower()).__getattribute__(module_type)


    project=context['project']
    i = project.modules.aggregate(Max('tab_position'))['tab_position__max'] + 1
    if module_type == 'SimplePage':
        name = None
    else:
        name = module_type.lower() 

    module = model(
            project=project,
            name=name,
            label=tab_name,
            tab_position=i
        )
    module.save()
    
    js_target.redirect(module.djity_url(context))
Ejemplo n.º 4
0
def _validate_rules(rules):
    project_name = _get_project_name()

    for app in rules.iterkeys():
        try:
            get_app(app, emptyOK=True)
        except ImproperlyConfigured:
            if app != project_name:
                raise
Ejemplo n.º 5
0
    def haystack_load_apps():
        # Do all, in an INSTALLED_APPS sorted order.
        items = []

        for app in settings.INSTALLED_APPS:
            app_label = app.split('.')[-1]

            try:
                get_app(app_label)
            except ImproperlyConfigured:
                continue  # Intentionally allow e.g. apps without models.py

            items.append(app_label)

        return items
Ejemplo n.º 6
0
    def haystack_load_apps():
        # Do all, in an INSTALLED_APPS sorted order.
        items = []

        for app in settings.INSTALLED_APPS:
            app_label = app.split('.')[-1]

            try:
                get_app(app_label)
            except ImproperlyConfigured:
                continue  # Intentionally allow e.g. apps without models.py

            items.append(app_label)

        return items
Ejemplo n.º 7
0
def dump(request):
    response = HttpResponse(mimetype="application/ms-excel")
    response["Content-Disposition"] = "attachment; filename=PennCycle-Database-Dump-%s.xls" % (
        str(datetime.datetime.today())
    )

    wb = xlwt.Workbook()
    excel_date_fmt = "M/D/YY h:mm"
    datestyle = xlwt.XFStyle()
    datestyle.num_format_str = excel_date_fmt
    plainstyle = xlwt.XFStyle()

    app = get_app("app")
    models = get_models(app)

    for model in models:
        name = model.__name__
        print name
        if name == "Plan":
            break
        ws = wb.add_sheet(slugify(name))
        xl_export(model, ws, datestyle, plainstyle)

    wb.save(response)
    return response
Ejemplo n.º 8
0
def model_tree(app_label_or_app):
    '''
    Get model order by their relations
    '''
    from django.db.models import Model
    from django.db.models.loading import get_app, get_models
    if isinstance(app_label_or_app, basestring):
        app = get_app(app_label_or_app)
    else:
        app = app_label_or_app
        assert isinstance(app, Model)
        
    models = get_models(app)
    tree = modeldict()
    for model in models:
        meta = model._meta
        #model_name = '.'.join( [ meta.app_label, meta.module_name ] )
        deps = []
        tree[model] = deps
        
        for rel_model in meta.many_to_many:
            deps.append(rel_model.rel.to)
        #import ipdb; ipdb.set_trace()
    return tree
    
Ejemplo n.º 9
0
def svn_app_version(appname=None, fail_silently=bool(not settings.DEBUG)):
    """
    foo.app {% svn_app_version "foo.app" %}
    project {% svn_app_version %}
    """
    cname = 'svn_app_version'
    if appname: cname += '.' + appname
    version = cache.get(cname)
    if not version:
        if not appname:
            ## RED_FLAG: hard coded relative root!
            version = get_svn_revision(dn(dn(dn(abspath(__file__)))))
        elif appname == 'django':
            version = get_svn_revision()
        elif appname not in settings.INSTALLED_APPS:
            version = 'SVN-None'
        else:
            try:
                module = get_app(appname)
            except:
                if not fail_silently: raise
                version = 'SVN-Error'
            else:
                version = get_svn_revision(dn(abspath(module.__file__)))
        cache.set(cname, version, 60*60*24*30)
    return version
Ejemplo n.º 10
0
def get_view_names(seo_views):
    output = []
    for name in seo_views:
        try:
            app = get_app(name)
        except:
            output.append(name)
        else:
            app_name = app.__name__.split(".")[:-1]
            app_name.append("urls")
            try:
                urls = __import__(".".join(app_name)).urls
            except (ImportError, AttributeError):
                output.append(name)
            else:
                for url in urls.urlpatterns:
                    if support_transurlvania:
                        if isinstance(url, LangSelectionRegexURLResolver):
                            for url_trans in url.url_patterns:
                                if url_trans.name:
                                    output.append(url_trans.name)
                        else:
                            if hasattr(url, 'name') and url.name:
                                output.append(url.name)
                    else:
                        if hasattr(url, 'name') and url.name:
                            output.append(url.name)
                            
    output = list(set(output))
    output.sort()
    return output
Ejemplo n.º 11
0
def project_entity_content():
        from django.conf import settings
        from base.translation import DataTranslation, _ugettext_ as _
        from django.contrib.contenttypes.models import ContentType
        from django.db.models.loading import get_app
        from django.db import models
        from django.core.urlresolvers import reverse
        model_list=[]
        relations=[]
        apps=[]
        for application in settings.INSTALLED_APPS:
                app_label=application.split(".")[-1]
                if app_label in ("admin","sessions"): continue
                app=get_app(app_label)
                ms=[]
                for i in dir(app):
                        try:
                                model=app.__getattribute__(i)
                                if issubclass(model, models.Model) and not model._meta.abstract and model._meta.app_label==app_label:
                                                model_list.append(model)
                                                for f in model._meta.fields:
                                                        if isinstance(f, models.ForeignKey):
                                                                relations.append((f, model._meta, f.rel.to._meta))
                                                ms.append(model._meta)
                        except: pass
                apps.append((app_label,ms))
        t=Context({"entities": [entity_diagram(model) for model in model_list], 
                "relations":[render_relation(relation) for relation in relations],
                "applications": [render_application(app) for app in apps],
                })
        return t
Ejemplo n.º 12
0
 def get(self, request, *args, **kwargs):
     app = get_app('app')
     models = [{'name': model.__name__, 'title': model._meta.verbose_name}
               for model in get_models(app)
               if not model._meta.abstract
              ]
     return self.render_to_response(models)
Ejemplo n.º 13
0
    def test_model_requests(self):
        """
        Создаем запись POST-ом, потом читаем GET-ом и убеждаемся, что получили то, что сохранили
        """

        models = get_models(get_app('dynamic_models'))
        post_data = {}

        for model in models:
            post_data[model.__name__] = {}
            for field in model._meta.fields:
                if field.get_internal_type() == "IntegerField":
                    post_data[model.__name__][field.name] = randrange(10000)
                elif field.get_internal_type() == "DateField":
                    post_data[model.__name__][field.name] = rnd_date().strftime("%d.%m.%Y")
                if field.get_internal_type() == "CharField":
                    post_data[model.__name__][field.name] = rnd_str()

        # POST
        for model_name in post_data:
            query = {'model': model_name}
            query.update(post_data[model_name])
            resp = self.client.post('/model/', query)
            self.assertEqual(resp.status_code, 200)

        # GET
        for model_name in post_data:
            url = '/model/?model=%s' % model_name
            resp = self.client.get(url)
            json_response = json.loads(resp.content)
            self.assertEqual(resp.status_code, 200)
            for value in post_data[model_name].values():
                self.assertIn(value, json_response['values'][0])
Ejemplo n.º 14
0
 def get_objects(self):
     objects = list()
     app = get_app(self.application)
     models = get_models(app)
     for model in models:
         objects.extend(model.objects.all())
     return objects
Ejemplo n.º 15
0
    def get_profile(self):
        """
        Returns site-specific profile for this user. Raises
        SiteProfileNotAvailable if this site does not allow profiles.
        """
        if not hasattr(self, '_profile_cache'):
            from django.conf import settings
            if not getattr(settings, 'AUTH_PROFILE_MODULE', False):
                raise SiteProfileNotAvailable('You need to set AUTH_PROFILE_MO'
                                              'DULE in your project settings')
            try:
                app_label, model_name = settings.AUTH_PROFILE_MODULE.split('.')
            except ValueError:
                raise SiteProfileNotAvailable('app_label and model_name should'
                        ' be separated by a dot in the AUTH_PROFILE_MODULE set'
                        'ting')

            try:
                ### model = models.get_model(app_label, model_name)
                from django.db.models.loading import get_app
                app = get_app(app_label)
                model = getattr(app, model_name, None)

                if model is None:
                    raise SiteProfileNotAvailable('Unable to load the profile '
                        'model, check AUTH_PROFILE_MODULE in your project sett'
                        'ings')
                ### self._profile_cache = model._default_manager.using(self._state.db).get(user__id__exact=self.id)
                self._profile_cache = model.get_userprofile(self.get_id)

                ### self._profile_cache.user = self
            except (ImportError, ImproperlyConfigured):
                raise SiteProfileNotAvailable
        return self._profile_cache
Ejemplo n.º 16
0
def get_project_app(app_label):
    for app in settings.PROJECT_APPS:
        if app_label == app.split('.')[-1]:
            break
    else:
        raise ImproperlyConfigured("App with label %s could not be found" % app_label)
    return get_app(app_label)
Ejemplo n.º 17
0
    def handle(self, *args, **options):
        if len(args) < 1:
            raise CommandError("need at least one unit test TestClass")
        verbosity = int(options.get("verbosity", 0))

        call_command("zap", noinput=False, verbosity=verbosity, load_initial_data=False)
        #        for app in get_apps():
        #            call_command('sqlsequencereset', app)

        for test in args:
            parts = test.split(".")
            if len(parts) != 2:
                raise ValueError(
                    "Test label '%s' should be of the form app.TestCase or app.TestCase.test_method" % test
                )
            app_module = get_app(parts[0])
            test_module = get_tests(app_module)
            TestClass = getattr(app_module, parts[1], None)
            if TestClass is None:
                if test_module:
                    TestClass = getattr(test_module, parts[1], None)

            if issubclass(TestClass, unittest.TestCase):
                for f in TestClass.fixtures:
                    if verbosity > 0:
                        print "Looking for fixture `%s`" % f
                    call_command("xloaddata", f, verbosity=verbosity)
Ejemplo n.º 18
0
def get_project_app(app_label):
    for app in settings.PROJECT_APPS:
        if app_label == app.split('.')[-1]:
            break
    else:
        raise ImproperlyConfigured("App with label %s could not be found" % app_label)
    return get_app(app_label)
Ejemplo n.º 19
0
def pytest_runtest_call(item):
    # HACK: sequences arent reset for postgres
    global _HAS_FIXED_SEQUENCES

    if not _HAS_FIXED_SEQUENCES:
        import os

        os.environ['DJANGO_COLORS'] = 'nocolor'

        from django.core.management import call_command
        from django.conf import settings
        from django.db import connection
        from django.db.models.loading import get_app
        from StringIO import StringIO

        commands = StringIO()
        cursor = connection.cursor()

        for app in settings.INSTALLED_APPS:
            label = app.split('.')[-1]
            if get_app(label, emptyOK=True):
                call_command('sqlsequencereset', label, stdout=commands)

        value = commands.getvalue()
        if value:
            cursor.execute(value)

        _HAS_FIXED_SEQUENCES = True
Ejemplo n.º 20
0
    def create_history_model(self, model):
        """
        Creates a historical model to associate with the model provided.
        """
        attrs = {'__module__': self.module}

        app_module = '%s.models' % model._meta.app_label
        if model.__module__ != self.module:
            # registered under different app
            attrs['__module__'] = self.module
        elif app_module != self.module:
            if apps is None:  # Django < 1.7
                # has meta options with app_label
                app = loading.get_app(model._meta.app_label)
                attrs['__module__'] = app.__name__  # full dotted name
            else:
                # Abuse an internal API because the app registry is loading.
                app = apps.app_configs[model._meta.app_label]
                attrs['__module__'] = app.name  # full dotted name

        fields = self.copy_fields(model)
        attrs.update(fields)
        attrs.update(self.get_extra_fields(model, fields))
        # type in python2 wants str as a first argument
        attrs.update(Meta=type(str('Meta'), (), self.get_meta_options(model)))
        name = 'Historical%s' % model._meta.object_name
        registered_models[model._meta.db_table] = model
        return python_2_unicode_compatible(type(str(name), self.bases, attrs))
Ejemplo n.º 21
0
    def add_yesno_categories(self):
        app = get_app('dms')
        ResponseCategoryModel = app.poll_response.ResponseCategory

        """
        This creates a generic yes/no poll categories for a particular poll
        """
        yes_category = ResponseCategoryModel.objects(**dict(poll=self, name='yes')).first() or \
                        ResponseCategoryModel(**dict(name='yes', poll=self)).save()
        no_category = ResponseCategoryModel.objects(**dict(poll=self, name='no')).first() or \
                        ResponseCategoryModel(**dict(name='no', poll=self)).save()
        unknown_category = ResponseCategoryModel.objects(**dict(poll=self, name='unknown')).first() or \
                        ResponseCategoryModel(**dict(name='unknown', poll=self, default=True, error_category=True)).save()

        # add one rule to yes category per language
        no_words = getattr(settings, 'NO_WORDS', NO_WORDS)
        yes_words = getattr(settings, 'YES_WORDS', YES_WORDS)

        no_rule_string = '|'.join(no_words)
        yes_rule_string = '|'.join(yes_words)

        startswith_template = getattr(settings, 'STARTSWITH_PATTERN_TEMPLATE', STARTSWITH_PATTERN_TEMPLATE)

        Rule(**dict(response_category=yes_category,
                    regex=(startswith_template % yes_rule_string),
                    rule_type=Rule.TYPE_REGEX,
                    rule_string=(startswith_template % yes_rule_string))).save()

        Rule(**dict(response_category=no_category,
                    regex=(startswith_template % no_rule_string),
                    rule_type=Rule.TYPE_REGEX,
                    rule_string=(startswith_template % no_rule_string))).save()
Ejemplo n.º 22
0
    def add_yesno_categories(self):
        app = get_app('dms')
        ResponseCategoryModel = app.poll_response.ResponseCategory
        """
        This creates a generic yes/no poll categories for a particular poll
        """
        yes_category = ResponseCategoryModel.objects(**dict(poll=self, name='yes')).first() or \
                        ResponseCategoryModel(**dict(name='yes', poll=self)).save()
        no_category = ResponseCategoryModel.objects(**dict(poll=self, name='no')).first() or \
                        ResponseCategoryModel(**dict(name='no', poll=self)).save()
        unknown_category = ResponseCategoryModel.objects(**dict(poll=self, name='unknown')).first() or \
                        ResponseCategoryModel(**dict(name='unknown', poll=self, default=True, error_category=True)).save()

        # add one rule to yes category per language
        no_words = getattr(settings, 'NO_WORDS', NO_WORDS)
        yes_words = getattr(settings, 'YES_WORDS', YES_WORDS)

        no_rule_string = '|'.join(no_words)
        yes_rule_string = '|'.join(yes_words)

        startswith_template = getattr(settings, 'STARTSWITH_PATTERN_TEMPLATE',
                                      STARTSWITH_PATTERN_TEMPLATE)

        Rule(**dict(response_category=yes_category,
                    regex=(startswith_template % yes_rule_string),
                    rule_type=Rule.TYPE_REGEX,
                    rule_string=(startswith_template %
                                 yes_rule_string))).save()

        Rule(**dict(response_category=no_category,
                    regex=(startswith_template % no_rule_string),
                    rule_type=Rule.TYPE_REGEX,
                    rule_string=(startswith_template %
                                 no_rule_string))).save()
Ejemplo n.º 23
0
 def test_username_non_unique(self):
     "A non-unique USERNAME_FIELD should raise a model validation error."
     new_io = StringIO()
     get_validation_errors(new_io, get_app('auth'))
     self.assertIn(
         "The USERNAME_FIELD must be unique. Add unique=True to the field parameters.",
         new_io.getvalue())
Ejemplo n.º 24
0
    def test_model_requests(self):
        """
        Создаем запись POST-ом, потом читаем GET-ом и убеждаемся, что получили то, что сохранили
        """

        models = get_models(get_app('dynamic_models'))
        post_data = {}

        for model in models:
            post_data[model.__name__] = {}
            for field in model._meta.fields:
                if field.get_internal_type() == "IntegerField":
                    post_data[model.__name__][field.name] = randrange(10000)
                elif field.get_internal_type() == "DateField":
                    post_data[model.__name__][
                        field.name] = rnd_date().strftime("%d.%m.%Y")
                if field.get_internal_type() == "CharField":
                    post_data[model.__name__][field.name] = rnd_str()

        # POST
        for model_name in post_data:
            query = {'model': model_name}
            query.update(post_data[model_name])
            resp = self.client.post('/model/', query)
            self.assertEqual(resp.status_code, 200)

        # GET
        for model_name in post_data:
            url = '/model/?model=%s' % model_name
            resp = self.client.get(url)
            json_response = json.loads(resp.content)
            self.assertEqual(resp.status_code, 200)
            for value in post_data[model_name].values():
                self.assertIn(value, json_response['values'][0])
Ejemplo n.º 25
0
def project_entity_content():
    from django.conf import settings
    from base.translation import DataTranslation, _ugettext_ as _
    from django.contrib.contenttypes.models import ContentType
    from django.db.models.loading import get_app
    from django.db import models
    from django.core.urlresolvers import reverse
    model_list = []
    relations = []
    apps = []
    for application in settings.INSTALLED_APPS:
        app_label = application.split(".")[-1]
        if app_label in ("admin", "sessions"): continue
        app = get_app(app_label)
        ms = []
        for i in dir(app):
            try:
                model = app.__getattribute__(i)
                if issubclass(
                        model, models.Model
                ) and not model._meta.abstract and model._meta.app_label == app_label:
                    model_list.append(model)
                    for f in model._meta.fields:
                        if isinstance(f, models.ForeignKey):
                            relations.append((f, model._meta, f.rel.to._meta))
                    ms.append(model._meta)
            except:
                pass
        apps.append((app_label, ms))
    t = Context({
        "entities": [entity_diagram(model) for model in model_list],
        "relations": [render_relation(relation) for relation in relations],
        "applications": [render_application(app) for app in apps],
    })
    return t
Ejemplo n.º 26
0
def dump(request):
    response = HttpResponse(mimetype="application/ms-excel")
    response['Content-Disposition'] = 'attachment; filename=PennCycle-Database-Dump-%s.xls' % (str(datetime.datetime.today()))

    if not request.user.is_staff:
        return HttpResponseForbidden()

    wb = xlwt.Workbook()
    excel_date_fmt = 'M/D/YY h:mm'
    datestyle = xlwt.XFStyle()
    datestyle.num_format_str = excel_date_fmt
    plainstyle = xlwt.XFStyle()

    app = get_app('app')
    models = get_models(app)

    for model in models:
        name = model.__name__
        print name
        if name == 'Plan':
            break
        ws = wb.add_sheet(slugify(name))
        xl_export(model, ws, datestyle, plainstyle)

    wb.save(response)
    return response
Ejemplo n.º 27
0
 def is_yesno_poll(self):
     app = get_app('dms')
     ResponseCategoryModel = app.poll_response.ResponseCategory
     return ResponseCategoryModel.objects(poll=self).count() == 3 and \
            ResponseCategoryModel.objects(poll=self, name='yes').count() and \
            ResponseCategoryModel.objects(poll=self, name='no').count() and \
            ResponseCategoryModel.objects(poll=self, name='unknown').count()
Ejemplo n.º 28
0
    def build_suite(self, test_labels, extra_tests=None, **kwargs):
        """ Default behaviour is augmented to improve test discovery """
        sooper = super(XmlDjangoTestSuiteRunner,self)
        suite  = sooper.build_suite(test_labels, extra_tests=extra_tests, **kwargs)

        ## This section finds tests that were skipped due to
        ## duplicate app names. (code adapted from django.test.simple)
        for test_label in test_labels:
            all_apps = get_apps(test_label)
            if len(all_apps) > 1:
                leftover_apps = [ app for app in all_apps if app!=get_app(test_label) ]
                for app_module in leftover_apps:
                    # Check to see if a separate 'tests' module
                    # exists parallel to the "models" module
                    test_module = get_tests(app_module)
                    if test_module:
                        new_suite = unittest.defaultTestLoader.loadTestsFromModule(test_module)
                        if new_suite._tests:
                            suite.addTests(new_suite._tests)
                            msg       = "Discovered {N} extra tests for shadowed appname: {A}"
                            msg_kargs = dict(N=len(new_suite._tests), A=app_module.__name__)
                        else:
                            msg = "Discovered shadowed appname \"{A}\" but no tests were found"
                            msg_kargs = dict(A=app_module.__name__)
                        self.report(msg, **msg_kargs)
        return suite
Ejemplo n.º 29
0
    def fkeymap(self, obj, row, cols):
        """This method is used to map a foreign key.

        This method is responsible for recursively fetching and
        returning the necessary foreign key objects to ingest a foreign key
        into the database. 

        :return: A model object.
        """
        
        model = None
        app = get_app('datawarehouse')
        models = get_models(app)
        # attempt to match the specified table to a model and raise an exception if not found
        for m in models:
            if m._meta.db_table == obj['table']:
                model = m
                break
        if model == None:
            raise TableDoesNotExist("The database table " + obj['table'] + " does not exist.")
        
        sql_dict = {}
        # loop through the mapping object and create the object using data from the input file
        # if the value is an object, recursively call fkeymap. 
        for key, value in obj.iteritems():
            if key != 'table':
                if isinstance(value, unicode):
                    sql_dict[key] = (None if row[cols[value]] is "" else row[cols[value]]) 
                else:
                    sql_dict[key] = (None if self.fkeymap(value, row, cols) is "" else self.fkeymap(value, row, cols))
        m, created = model.objects.get_or_create(**sql_dict)
        return m
Ejemplo n.º 30
0
 def test_username_not_in_required_fields(self):
     "USERNAME_FIELD should not appear in REQUIRED_FIELDS."
     new_io = StringIO()
     get_validation_errors(new_io, get_app('auth'))
     self.assertIn(
         "The field named as the USERNAME_FIELD should not be included in REQUIRED_FIELDS on a swappable User model.",
         new_io.getvalue())
Ejemplo n.º 31
0
 def is_yesno_poll(self):
     app = get_app('dms')
     ResponseCategoryModel = app.poll_response.ResponseCategory
     return ResponseCategoryModel.objects(poll=self).count() == 3 and \
            ResponseCategoryModel.objects(poll=self, name='yes').count() and \
            ResponseCategoryModel.objects(poll=self, name='no').count() and \
            ResponseCategoryModel.objects(poll=self, name='unknown').count()
Ejemplo n.º 32
0
    def handle(self, **options):
        runner = simple.DjangoTestSuiteRunner(verbosity=0)
        err_msg = "Failed to migrate %s; see output for hints at missing dependencies:\n"
        hacks.patch_flush_during_test_db_creation()
        failures = 0
        for app_name in settings.INSTALLED_APPS:
            app_label = app_name.split(".")[-1]
            if app_name == 'south':
                continue

            try:
                Migrations(app_name)
            except NoMigrations:
                continue
            app = loading.get_app(app_label)

            verbosity = int(options.get('verbosity', 1))
            if verbosity >= 1:
                self.stderr.write("processing %s\n" % app_name)

            old_config = runner.setup_databases()
            try:
                call_command('migrate', app_label, noinput=True, verbosity=verbosity)
                for model in loading.get_models(app):
                    dummy = model._default_manager.exists()
            except (KeyboardInterrupt, SystemExit):
                raise
            except Exception, e:
                failures += 1
                if verbosity >= 1:
                    self.stderr.write(err_msg % app_name)
                    self.stderr.write("%s\n" % e)
            finally:
Ejemplo n.º 33
0
def checkAndCreateModelPermissions(appName):
    from django.db.models.loading import get_app
    from django.db import models
    app = get_app(appName)
    for i in dir(app):
        try:
            a = app.__getattribute__(i)
            if issubclass(a, models.Model):
                checkAndCreateModelPermission(a)
        except:
            pass
    try:
        ct = ContentType.objects.get_for_model(Transaction)
        Permission(content_type=ct,
                   codename='init_database',
                   name='Init database').save()
    except:
        pass
    try:
        ct = ContentType.objects.get_for_model(Group)
        Permission(content_type=ct,
                   codename='browse_' + Group.__name__.lower(),
                   name='Can browse %s' % Group.__name__).save()
    except:
        pass
Ejemplo n.º 34
0
    def safe_build_suite(self, test_labels, extra_tests=None, **kwargs):
        suite = unittest.TestSuite()

        if test_labels:
            for label in test_labels:
                try:
                    if '.' in label:
                        suite.addTest(build_test(label))
                    else:
                        app = get_app(label)
                        suite.addTest(build_suite(app))
                except Exception:
                    log.warning("Could not add test for label: %s" %label)
        else:
            for app in get_apps():
                try:
                    suite.addTest(build_suite(app))
                except Exception:
                    log.warning("Could not add tests for app: %s" %app)

        if extra_tests:
            for test in extra_tests:
                suite.addTest(test)

        return reorder_suite(suite, (TestCase,))
Ejemplo n.º 35
0
    def create_history_model(self, model):
        """
        Creates a historical model to associate with the model provided.
        """
        attrs = {'__module__': self.module}

        app_module = '%s.models' % model._meta.app_label
        if model.__module__ != self.module:
            # registered under different app
            attrs['__module__'] = self.module
        elif app_module != self.module:
            if apps is None:  # Django < 1.7
                # has meta options with app_label
                app = loading.get_app(model._meta.app_label)
                attrs['__module__'] = app.__name__  # full dotted name
            else:
                # Abuse an internal API because the app registry is loading.
                app = apps.app_configs[model._meta.app_label]
                attrs['__module__'] = app.name      # full dotted name

        fields = self.copy_fields(model)
        attrs.update(fields)
        attrs.update(self.get_extra_fields(model, fields))
        # type in python2 wants str as a first argument
        attrs.update(Meta=type(str('Meta'), (), self.get_meta_options(model)))
        name = 'Historical%s' % model._meta.object_name
        registered_models[model._meta.db_table] = model
        return python_2_unicode_compatible(
            type(str(name), self.bases, attrs))
def get_schematics_models(app_name):
    app = get_app(app_name)
    models =  get_models(app)
    all_models = []
    for model in models:
        all_models += SchematicsModel.from_django(model)
    return all_models
Ejemplo n.º 37
0
def pytest_runtest_call(item):
    # HACK: sequences arent reset for postgres
    global _HAS_FIXED_SEQUENCES

    if not _HAS_FIXED_SEQUENCES:
        import os

        os.environ['DJANGO_COLORS'] = 'nocolor'

        from django.core.management import call_command
        from django.conf import settings
        from django.db import connection
        from django.db.models.loading import get_app
        from StringIO import StringIO

        commands = StringIO()
        cursor = connection.cursor()

        for app in settings.INSTALLED_APPS:
            label = app.split('.')[-1]
            if get_app(label, emptyOK=True):
                call_command('sqlsequencereset', label, stdout=commands)

        value = commands.getvalue()
        if value:
            cursor.execute(value)

        _HAS_FIXED_SEQUENCES = True
Ejemplo n.º 38
0
def add_new_model2(request, model_name):
    if (model_name.lower() == model_name):
        normal_model_name = model_name.capitalize()
    else:
        normal_model_name = model_name


#     app_list = get_apps()
#     for app in app_list:
    app = get_app('django_obit_desk2')
    for model in get_models(app):
        if model.__name__ == normal_model_name:
            form = modelform_factory(model)

            if normal_model_name == 'Death_notice':
                dn_name = model._meta.verbose_name
                form = Death_noticeForm
                service_form = ServiceFormSet
                dn_os_formset = DeathNoticeOtherServicesFormSet

            if request.method == 'POST':
                form = form(request.POST)
                service_form = service_form(request.POST)
                dn_os_formset = DeathNoticeOtherServicesFormSet(request.POST)
                if form.is_valid() and service_form.is_valid(
                ) and dn_os_formset.is_valid():
                    try:
                        if normal_model_name == 'Death_notice':
                            new_obj = form.save(commit=False)
                            new_obj.funeral_home = request.user
                            new_obj.save()
                            service_form = ServiceFormSet(request.POST,
                                                          instance=new_obj)
                            service_form.save()
                            dn_os_formset = DeathNoticeOtherServicesFormSet(
                                request.POST, instance=new_obj)
                            dn_os_formset.save()
                        else:
                            new_obj = form.save()
                    except forms.ValidationError, error:
                        new_obj = None

                    if new_obj:
                        return HttpResponse('<script type="text/javascript">opener.dismissAddAnotherPopup(window, "%s", "%s");</script>' % \
                               (escape(new_obj._get_pk_val()), escape(new_obj)))
            else:
                form = form()

            page_context = {
                'form': form,
                'service_form': service_form,
                'other_services_formset': dn_os_formset,
                'field': normal_model_name,
                'dn_verbose_name': dn_name,
                'dn_app_name': app,
            }
            return render_to_response('dn_popup2.html',
                                      page_context,
                                      context_instance=RequestContext(request))
Ejemplo n.º 39
0
def unpatch_models(app_name, unpatch_info):
    from django.db.models import Model
    funcToMethod(_default_save, Model, method_name='save')

    app = get_app(app_name)
    for model in get_models(app):
        restore_m2m_descriptors(model, unpatch_info[model]['descriptors'])
        model.objects = unpatch_info[model]['manager']
Ejemplo n.º 40
0
 def test_username_not_in_required_fields(self):
     "USERNAME_FIELD should not appear in REQUIRED_FIELDS."
     new_io = StringIO()
     get_validation_errors(new_io, get_app("auth"))
     self.assertIn(
         "The field named as the USERNAME_FIELD should not be included in REQUIRED_FIELDS on a swappable User model.",
         new_io.getvalue(),
     )
Ejemplo n.º 41
0
    def get_discovery_root(self, label):
        try:
            models_module = get_app(label)
            discovery_root = os.path.dirname(models_module.__file__)
        except ImproperlyConfigured:
            discovery_root = os.path.join(settings.ROOT_DIR, label)

        return discovery_root
Ejemplo n.º 42
0
def unpatch_models(app_name, unpatch_info):
    from django.db.models import Model
    funcToMethod(_default_save, Model, method_name='save')

    app = get_app(app_name)
    for model in get_models(app):
        restore_m2m_descriptors(model, unpatch_info[model]['descriptors'])
        model.objects = unpatch_info[model]['manager']
Ejemplo n.º 43
0
 def __init__(self, admin_site, app_label, model_name, page, **initkwargs):
     self.admin_site = admin_site
     self.app_label = app_label
     self.model_name = model_name
     self.page = page
     self.app = get_app(self.app_label)
     self.model = get_model(self.app_label, self.model_name)
     return super(CSVImporter, self).__init__(**initkwargs)
Ejemplo n.º 44
0
 def test_model_registering(self):
     test_app = get_app(app_label="tests")
     models = get_models(
         app_mod=test_app, include_auto_created=False, include_deferred=False, include_swapped=False
     )
     default_registered = len(reversion.get_registered_models())
     custom_registered = len(custom_revision_manager.get_registered_models())
     self.assertEqual(default_registered + custom_registered, len(models))
Ejemplo n.º 45
0
    def handle_noargs(self, **options):
        app = get_app('services')
        try:
            boris_config = apps.get_app_config('boris')
        except:
            raise EnvironmentError(
                'Cannot find app `boris`. App configs are: %s' %
                apps.get_app_configs())
        update_contenttypes(boris_config, 2, interactive=False)
        app_models = models.get_models(app)
        # This will hold the permissions we're looking for as
        # (content_type, (codename, name))
        searched_perms = list()
        # The codenames and ctypes that should exist.
        ctypes = set()
        for model in app_models:
            opts = model._meta
            # We can't use `get_for_model` here since it doesn't return
            # the correct `ContentType` for proxy models.
            # see https://code.djangoproject.com/ticket/17648
            app_label, model = opts.app_label, opts.object_name.lower()
            if app_label == 'services' and model == 'encounter':
                ctype = ContentType.objects.get_by_natural_key(
                    app_label, model)
                ctypes.add(ctype)
                for perm in _get_all_permissions(opts, model):
                    searched_perms.append((ctype, perm))

        # Find all the Permissions that have a content_type for a model we're
        # looking for. We don't need to check for codenames since we already have
        # a list of the ones we're going to create.
        all_perms = set(
            Permission.objects.filter(content_type__in=ctypes, ).values_list(
                "content_type", "codename"))

        group, created = Group.objects.get_or_create(name=u'Terén')
        print 'group: %s' % group
        if created:
            print 'ERROR: skupina Teren neexistovala!'
            return
        for ctype, (codename, name) in searched_perms:
            if (ctype.pk, codename) not in all_perms:
                Permission.objects.filter(codename=codename,
                                          name=name).delete()
                perm = Permission.objects.create(codename=codename,
                                                 name=name,
                                                 content_type=ctype)
                group.permissions.add(perm)
                sys.stdout.write("Adding encounter permission '%s'" % perm)

        for perm in Permission.objects.filter(
                codename__endswith='_groupcontact'):
            group.permissions.add(perm)
            sys.stdout.write("Adding group encounter permission '%s'" % perm)

        for perm in Permission.objects.filter(codename__endswith='_encounter'):
            group.permissions.add(perm)
            sys.stdout.write("Adding service permission '%s'" % perm)
Ejemplo n.º 46
0
 def get_app_dict(app_label):
     app=get_app(app_label)
     dict_data={
         "verbose_name":u"%(name)s"%{
             'name':hasattr(app, "verbose_name") and app.verbose_name or app_label
         },
         "models":[]
     }
     return app,dict_data
Ejemplo n.º 47
0
    def haystack_get_models(label):
        app_or_model = is_app_or_model(label)

        if app_or_model == APP:
            app_mod = get_app(label)
            return get_models(app_mod)
        else:
            app_label, model_name = label.rsplit('.', 1)
            return [get_model(app_label, model_name)]
Ejemplo n.º 48
0
 def source(self):
     app = get_app('dms')
     SettingModel = app.admin_setting.AdminSetting
     volunteer_profiles = SettingModel._lookup("enable_volunteer_profiles")
     if volunteer_profiles and volunteer_profiles.yes_no:
         profile = self._mobile_user()
         return profile.name if profile else self.SENDER
     else:
         return self.SENDER
Ejemplo n.º 49
0
 def get_app_package(app_label):
     app_config = loading.get_app(app_label)
     if not app_config:
         return None
     if app_config.__package__ is None:
         app_config.__package__ = app_config.__name__.rpartition('.')[0]
     if app_config.__package__.endswith('.models'):
         return app_config.__package__[0:-len('.models')]
     return app_config.__package__
Ejemplo n.º 50
0
    def get_context_data(self, **kwargs):
        context = super(HomePageView, self).get_context_data(**kwargs)
        models = []

        for model in get_models(get_app('dynamic_models')):
            models.append([model.__name__, model._meta.verbose_name])

        context['models'] = models

        return context
Ejemplo n.º 51
0
 def test_model_registering(self):
     test_app = get_app(app_label="reversion_compare_test_app")
     models = get_models(app_mod=test_app,
                         include_auto_created=False,
                         include_deferred=False,
                         only_installed=True)
     default_registered = len(reversion.get_registered_models())
     custom_registered = len(
         custom_revision_manager.get_registered_models())
     self.assertEqual(default_registered + custom_registered, len(models))
Ejemplo n.º 52
0
 def test_model_registering(self):
     test_app = get_app(app_label="tests")
     models = get_models(app_mod=test_app,
                         include_auto_created=False,
                         include_deferred=False,
                         include_swapped=False)
     default_registered = len(reversion.get_registered_models())
     custom_registered = len(
         custom_revision_manager.get_registered_models())
     self.assertEqual(default_registered + custom_registered, len(models))
Ejemplo n.º 53
0
 def handle(self, *args, **options):
     if len(args) < 1:
         if options['all_applications']:
             applications = get_apps()
         else:
             raise CommandError("need one or more arguments for appname")
     else:
         try:
             applications = [get_app(label) for label in args]
         except ImproperlyConfigured, e:
             raise CommandError("Specified application not found: %s" % e)
 def forwards(self, orm):
     contenttypes = orm['contenttypes.ContentType'].objects
     removed = set()
     for ct in contenttypes.filter(model__endswith='_hist')\
                           .exclude(name__endswith=' history'):
         removed.add(ct.app_label)
         Permission.objects.filter(content_type=ct).delete()
         ct.delete()
     for app_label in removed:
         app = get_app(app_label)
         update_contenttypes(app, None)
         create_permissions(app, None, 2)
Ejemplo n.º 55
0
        def normalize(layout):
            try:
                app_label, model_name = layout.split(".")
            except ValueError:
                app_label = self.model._meta.app_label
                model_name = layout
            except AttributeError:
                app_label = layout._meta.app_label
                model_name = layout._meta.object_name

            # we cannot use models.get_model because this class could be
            # abstract.
            return getattr(get_app(app_label), model_name)
Ejemplo n.º 56
0
    def haystack_get_models(label):
        try:
            app_mod = get_app(label)
            if app_mod is not None:
                return get_models(app_mod=app_mod)
        except ImproperlyConfigured:
            pass

        if '.' not in label:
            raise ImproperlyConfigured("No installed application has the label %s" % label)

        app_label, model_name = label.rsplit('.', 1)
        return [get_model(app_label, model_name)]
Ejemplo n.º 57
0
def patch_models(app_name):
    unpatch_info = {}
    app = get_app(app_name)
    for model in get_models(app):
        unpatch_info[model] = dict(manager=model.objects,
                                   descriptors=extract_m2m_descriptors(model))
        memorify_m2m_descriptors(model)
        model.objects = MemoryManager(model)

    from django.db.models import Model
    Model.save = memory_save

    return unpatch_info
Ejemplo n.º 58
0
def load_fixtures_for_app(sender, **kwargs):
    app_name = kwargs.get("app")
    if not app_name: return

    print u"Running autoload fixtures for %s:" % app_name
    for model in get_models(get_app(app_name)):
        model_name = model.__name__.lower()
        print u" > %s:%s" % (app_name, model_name)
        fixture_path = "%(app_name)s/fixtures/%(model_name)s.json" % {
            "app_name": app_name,
            "model_name": model_name
        }
        call_command("loaddata", fixture_path)