Ejemplo n.º 1
0
def create_related_fields(instance, related_fields, data):
    """
    Function used to create the related fields when creating a new object.

    Args:
        instance (object): The object whose related fields are going to be created
        related_fields (dict): Dict containing information about the related fields
        data (dict): Dict containing the actual data for the related fields
    """
    for field in related_fields:
        for item_data in data.get(field['data_string']):
            # Remove is_deleted key from dict (so update/create don't give errors)
            is_deleted = item_data.pop('is_deleted', False)

            if item_data and not is_deleted:
                # Websites are different than the other related fields.
                # For now just have it as an edge case in this function.
                # In the future we might want to change how websites are setup.
                if field['model'] == 'Website':
                    model = get_model('accounts', field['model'])
                    model.objects.create(account=instance, **item_data)
                else:
                    # Get the model
                    if field['model'] == 'SocialMedia':
                        model = get_model('socialmedia', field['model'])
                    else:
                        model = get_model('utils', field['model'])
                    # Create new object from model and add to set
                    field_name = field['data_string']
                    getattr(instance, field_name).add(model.objects.create(**item_data))
Ejemplo n.º 2
0
def cron_post_save(sender, instance, **kwargs):
    """
    Finds and schedules tasks for any CronEvents bound to the given instance.

    Inputs:
    :sender: Which event type was saved
    :instance: Specific instance saved
    """
    CronEvent = get_model("myemails", "CronEvent")
    EmailTask = get_model("myemails", "EmailTask")
    content_type = ContentType.objects.get_for_model(sender)
    cron_event_kwargs = {
        "model": content_type,
        "owner": instance.product.owner if hasattr(instance, "product") else instance.owner,
    }
    # Gets all CronEvents for this company and model...
    events = list(CronEvent.objects.filter(**cron_event_kwargs))
    # ...and all tasks scheduled for this instance.
    tasks = EmailTask.objects.filter(object_id=instance.pk, object_model=content_type)
    triggered_events = {task_.related_event for task_ in tasks}
    for event in triggered_events:
        if event in events:
            # If an event is already scheduled, remove it from the list of
            # events to be scheduled.
            events.remove(event)
    for event in events:
        # Schedule all remaining events.
        EmailTask.objects.create(act_on=instance, related_event=event).schedule()
Ejemplo n.º 3
0
def create_user(id, save=True, is_superuser=False):
    model = get_model("users", "User")
    domain_member_model = get_model("domains", "DomainMember")
    domain_model = get_model("domains", "Domain")

    instance = model(
       username="******".format(id),
       email="user{0}@taiga.io".format(id),
       first_name="Foo{0}".format(id),
       last_name="Bar{0}".format(id)
    )

    instance.set_password(instance.username)
    if is_superuser:
        instance.is_staff = True
        instance.is_superuser = True

    instance.save()

    domain = domain_model.objects.get(pk=1)
    dm = domain_member_model.objects.create(user=instance,
                                            email=instance.email,
                                            domain=domain)
    if id == 1:
        dm.is_owner = True
        dm.is_staff = True
        dm.save()

    return instance
Ejemplo n.º 4
0
    def __new__(cls, name, bases, attrs):
        # If this isn't a subclass of Model, don't do anything special.
        try:
            if not filter(lambda b: issubclass(b, Model), bases):
                return super(ModelBase, cls).__new__(cls, name, bases, attrs)
        except NameError:
            # 'Model' isn't defined yet, meaning we're looking at Django's own
            # Model class, defined below.
            return super(ModelBase, cls).__new__(cls, name, bases, attrs)

        # Create the class.
        new_class = type.__new__(cls, name, bases, {'__module__': attrs.pop('__module__')})
        new_class.add_to_class('_meta', Options(attrs.pop('Meta', None)))
        new_class.add_to_class('DoesNotExist', types.ClassType('DoesNotExist', (ObjectDoesNotExist,), {}))

        # Build complete list of parents
        for base in bases:
            # TODO: Checking for the presence of '_meta' is hackish.
            if '_meta' in dir(base):
                new_class._meta.parents.append(base)
                new_class._meta.parents.extend(base._meta.parents)


        if getattr(new_class._meta, 'app_label', None) is None:
            # Figure out the app_label by looking one level up.
            # For 'django.contrib.sites.models', this would be 'sites'.
            model_module = sys.modules[new_class.__module__]
            new_class._meta.app_label = model_module.__name__.split('.')[-2]

        # Bail out early if we have already created this class.
        m = get_model(new_class._meta.app_label, name, False)
        if m is not None:
            return m

        # Add all attributes to the class.
        for obj_name, obj in attrs.items():
            new_class.add_to_class(obj_name, obj)

        # Add Fields inherited from parents
        for parent in new_class._meta.parents:
            for field in parent._meta.fields:
                # Only add parent fields if they aren't defined for this class.
                try:
                    new_class._meta.get_field(field.name)
                except FieldDoesNotExist:
                    field.contribute_to_class(new_class, field.name)

        if getattr(new_class._meta, 'row_level_permissions', False):
            from django.contrib.auth.models import RowLevelPermission
            gen_rel = django.contrib.contenttypes.generic.GenericRelation(RowLevelPermission, object_id_field="model_id", content_type_field="model_ct")
            new_class.add_to_class("row_level_permissions", gen_rel)

        new_class._prepare()

        register_models(new_class._meta.app_label, new_class)
        # Because of the way imports happen (recursively), we may or may not be
        # the first class for this model to register with the framework. There
        # should only be one class for each model, so we must always return the
        # registered version.
        return get_model(new_class._meta.app_label, name, False)
Ejemplo n.º 5
0
    def create_default_tip(self, game):
        """
        Create a default tip for this club for game.
        """
        model = get_model('main', 'Tip')
        tip = model(
            club=self,
            game=game,
            is_default=True
        )
        tip.save()

        # Supercoach tips
        model = get_model('main', 'SupercoachTip')

        rnd = game.round
        if not rnd.is_finals:
            sc_count = constants.Supercoach.SC_COUNT_HOME_AWAY
        elif rnd.name != 'Grand Final':
            sc_count = constants.Supercoach.SC_COUNT_GRAND_FINAL
        else:
            sc_count = constants.Supercoach.SC_COUNT_FINALS

        for _ in range(sc_count):
            sc_tip = model(tip=tip)
            sc_tip.save()
Ejemplo n.º 6
0
 def _get_track(self, model_track, data_track):
     '''
     model_track is Gene, TSS, CDS, Isoform etc
     data_track is *data, *diff, etc.
     '''
     track_model = get_model('cuff', model_track)
     if model_track == 'tss':
         track_field = 'tss_group'
     else:
         track_field = model_track
     if data_track == 'diffdata':
         # these are 3 special cases where we have distribution
         # level diff data
         if model_track == 'gene':
             data_model = PromoterDiffData
         elif model_track == 'tss':
             data_model = SplicingDiffData
         elif model_track == 'cds':
             data_model = CDSDiffData
             track_field = 'gene'
     else:
         data_model = get_model('cuff', 
             '{track}{data}'.format(track=model_track, data=data_track)
             )
     return track_model, data_model, track_field
Ejemplo n.º 7
0
 def _step_3(self, request, app_name=None, model_name=None, temp_file_name=None, extra_context=None ):
     context = self._get_base_context(request, app_name, model_name)
     Model = get_model(app_name, model_name)
     extra_context = extra_context or {}
     if 'apply' in request.POST:
         Form = csv_processor_factory(app_name, model_name, temp_file_name)
         form = Form(request.POST, request.FILES)
         if form.is_valid():
             mapping = self.__get_mapping(form)
             Model = get_model(app_name, model_name)
             with open_csv(temp_file_name) as csv:
                 if form.cleaned_data['header']:
                     csv.next()
                 for i, row in enumerate(csv):
                     record, key = self._process_row(row, mapping)
                     try:
                         if key:
                             sample, _ = Model.objects.get_or_create(**key)
                         else:
                             sample = Model()
                         sample = update_model(request, sample, record, mapping)
                         sample.save()
                     except (IntegrityError, ObjectDoesNotExist), e:
                         messages.error(request, str(e))
             return redirect('%s:%s_%s_changelist' % (self.name, app_name, model_name.lower()))
Ejemplo n.º 8
0
	def set_value(self, name, value):
		"""
		Sets a value
		"""

		if self.pk is None:
			raise ValidationError("Save before storing value.")

		kwargs = {
			self.context_model: self,
			'name': name,
			'value': value
		}

		# Run within a savepoint
		# Else, IntegrityError in Postgres are not recoverable.
		try:
			sid = transaction.savepoint()

			v = get_model(self.context_app, self.context_holder)(**kwargs)
			v.save()

			transaction.savepoint_commit(sid)
		except IntegrityError:
			transaction.savepoint_rollback(sid)

			# Now here is some weird behavior in
			# stored_value.py. Django does not seems to reexecute the get_prep_value code, so we can't overwrite an existing value with a new FK.
			# Therefore we need to delete it...
			del kwargs['value']
			v = get_model(self.context_app, self.context_holder).objects.get(**kwargs).delete()
			self.set_value(name, value)
Ejemplo n.º 9
0
def list_tags(request, tagmodel=None):
    """
    Returns a list of JSON objects with a `name` and a `value` property that
    all start like your query string `q` (not case sensitive).
    """
    if not tagmodel or tagmodel not in TAG_MODELS:
        TAG_MODEL = get_model(*TAG_MODELS['default'])
    else:
        TAG_MODEL = get_model(*TAG_MODELS[tagmodel])
        
    query = request.GET.get('q', '')
    limit = request.GET.get('limit', MAX_SUGGESTIONS)
    try:
        request.GET.get('limit', MAX_SUGGESTIONS)
        limit = min(int(limit), MAX_SUGGESTIONS)  # max or less
    except ValueError:
        limit = MAX_SUGGESTIONS

    tag_name_qs = TAG_MODEL.objects.filter(name__icontains=query).\
        values_list('name', flat=True)

    if callable(getattr(TAG_MODEL, 'request_filter', None)):
        tag_name_qs = tag_name_qs.filter(TAG_MODEL.request_filter(request)).distinct()

    data = [{'name': n, 'value': n} for n in tag_name_qs[:limit]]

    return HttpResponse(json.dumps(data), content_type='application/json')
Ejemplo n.º 10
0
    def update_role_points(self, user_stories=None):
        RolePoints = get_model("userstories", "RolePoints")
        Role = get_model("users", "Role")

        # Get all available roles on this project
        roles = self.get_roles().filter(computable=True)
        if roles.count() == 0:
            return

        # Get point instance that represent a null/undefined
        null_points_value = self.points.get(value=None)

        # Iter over all project user stories and create
        # role point instance for new created roles.
        if user_stories is None:
            user_stories = self.user_stories.all()

        for story in user_stories:
            story_related_roles = Role.objects.filter(role_points__in=story.role_points.all())\
                                              .distinct()
            new_roles = roles.exclude(id__in=story_related_roles)
            new_rolepoints = [RolePoints(role=role, user_story=story, points=null_points_value)
                              for role in new_roles]
            RolePoints.objects.bulk_create(new_rolepoints)

        # Now remove rolepoints associated with not existing roles.
        rp_query = RolePoints.objects.filter(user_story__in=self.user_stories.all())
        rp_query = rp_query.exclude(role__id__in=roles.values_list("id", flat=True))
        rp_query.delete()
Ejemplo n.º 11
0
def remove_empty_groups():
    """Remove empty groups."""
    Group = get_model('groups', 'Group')
    Skill = get_model('groups', 'Skill')

    for model in [Group, Skill]:
        model.objects.annotate(mcount=Count('members')).filter(mcount=0).delete()
Ejemplo n.º 12
0
def get_by_ref(s, callback, module=None, app_label=None, field=None):
    if '@' in s:
        model, module_name = s.split('@')
        if module_name:
            app_label = None
            module = module_name
        if '.' in name:
            model, field = name.split('.')
    else:
        bits = s.rsplit('.', 3)
        if len(bits) == 1:
            model = bits[0]
        elif len(bits) == 2:
            app_label, model = bits
        else:
            app_label, model, field = bits
    
    if module and not app_label:
        app_label = get_app_label(module)        
    
    if app_label:
        from django.db.models.loading import get_model
        model = get_model(app_label, model)
    else:
        from django.db.models.loading import get_models
        for m in get_model():
            if m.__name__ == model:
                model = m
                break
    if not model:
        _pending_reference_lookups.setdefault((app_label, model), []).append((field, callback))
    else:
        _fire_ref_callback(model, field, callback)
Ejemplo n.º 13
0
  def __new__(cls, name, bases, attrs):
    """Creates a combined appengine and Django model.

    The resulting model will be known to both the appengine libraries and
    Django.
    """
    if name == 'BaseModel':
      # This metaclass only acts on subclasses of BaseModel.
      return super(PropertiedClassWithDjango, cls).__new__(cls, name,
                                                           bases, attrs)

    new_class = super(PropertiedClassWithDjango, cls).__new__(cls, name,
                                                              bases, attrs)

    new_class._meta = ModelOptions(new_class)
    new_class.objects = ModelManager(new_class)
    new_class._default_manager = new_class.objects
    new_class.DoesNotExist = types.ClassType('DoesNotExist',
                                             (ObjectDoesNotExist,), {})

    m = get_model(new_class._meta.app_label, name, False)
    if m:
      return m

    register_models(new_class._meta.app_label, new_class)
    return get_model(new_class._meta.app_label, name, False)
Ejemplo n.º 14
0
def get_list_of_child_categories_and_objects(app_label, model_name, cat_slug=None, cat_id=None):
    from django.db.models.loading import get_model

    Model=get_model(app_label,model_name)
    Category=get_model(app_label,'Category')

    if cat_slug:
        try:
            cat=Category.objects.get(slug=cat_slug)
        except Category.DoesNotExist:
            return []
    elif cat_id:
        try:
            cat = Category.objects.get(pk=cat_id)
        except Category.DoesNotExist:
            return []
    else:
        raise AttributeError("get_list_of_child_categories_and_objects got nothing to work on (no cat_slug, no cat_id)")



    mylist=[]
#        for c in cat.child_set.all():
    for c in Category.objects.filter(parent=cat.id):
        mylist.append({'id':c.id, 'priority':c.priority, 'url':c.get_absolute_url(), 'name':c.name, 'childtype':'Category','object':c})
    
    if model_name != 'Category':
#       for p in cat.smartpage_set.all():
        # There *must* be a nicer way to do this:
        for p in getattr(cat,model_name.lower()+'_set').all():
            mylist.append({'id':p.id, 'priority':p.priority, 'url':p.get_absolute_url(), 'name':p.name, 'childtype':model_name, 'object':p})
    
    mylist.sort(lambda f, s: cmp(f['priority'], s['priority']))

    return mylist
    def handle(self, *args, **options):
        """ """
        model_spec,trackable_model_spec = (None,None)
        try:
            (model_spec,trackable_model_spec) = args
        except ValueError:
            raise CommandError("Command takes two arguments")

        model_cls = get_model(*model_spec.split('.'))
        trackable_model_cls = get_model(*trackable_model_spec.split('.'))
        kwargs = {}

        if options.get('key_fields',{}):
            kwargs['key_fields'] = dict([ (pair.split(':')[0],pair.split(':')[1]) for pair in options.get('key_fields').split(',') ])
        if options.get('update_fields',{}):
            kwargs['update_fields'] = dict([ (pair.split(':')[0],pair.split(':')[1]) for pair in options.get('update_fields').split(',') ])
        if options.get('link_field',''):
            kwargs['link_field'] = options.get('link_field')
        if options.get('match_spec',''):
            kwargs['match_spec'] = options.get('match_spec')
        if options.get('max_records',0):
            kwargs['max_records'] = long(options.get('max_records'))
        if options.get('order_by',[]):
            kwargs['order_by'] = options.get('order_by').split(',')

        self.handle_model_data_migration( \
            model_cls, trackable_model_cls, **kwargs )
Ejemplo n.º 16
0
 def all(self):
     return ContentType.objects.get_for_models(
         get_model('leagues', 'DivisionSettings'),
         get_model('leagues', 'CupSettings'),
         get_model('matches', 'CupRound'),
         get_model('matches', 'DivisionRound')
     )
Ejemplo n.º 17
0
def edit_model(request, modelname, id):
    Model = get_model('admin_center', modelname)
    if not Model:
        Model = get_model('mainsite', modelname)
        if not Model:
            raise Http404
    if id == "add":
        model = Model()
        title = 'Добавить: ' + model._meta.verbose_name
    else:
        try:
            model = Model.objects.get(id=id)
        except Model.DoesNotExist:
            raise Http404
        title = 'Редактировать: ' + model._meta.verbose_name
    Form = modelform_factory(Model)
    if request.method == 'POST':
        form = Form(request.POST, instance=model)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(request.session['return_url'])
    else:
        request.session['return_url'] = request.GET['return_url']
        form = Form(instance=model)

    form.required_css_class = 'required'
    return direct_to_template(request, 'edit_model.html', {'form': form, 'id': id, 'title': title, 'modelname': modelname})
Ejemplo n.º 18
0
def threedee_test(request):
    cache_key = "threedee_test"
    response = safe_get_cache(cache_key)

    if not response:
        County = get_model("places","county")
        State = get_model("places","state")
        
        mo=State.objects.get(abbr="MO")

        
        values = []
        for county in County.objects.filter(state=mo)[:35].iterator():
            if (not county.population_demographics) or (not county.population_demographics.total) or (not county.area)\
                or (not county.socioeco_data) or (not county.socioeco_data.per_capita_income) or (not county.crime_data)\
                or (not county.crime_data.violent_crime):
                    continue
            
            pop_density = float(county.population_demographics.total)/float(county.area.sq_mi)
            if pop_density is 0:
                continue
            
            values.append(
                (pop_density, float(county.socioeco_data.per_capita_income), float(county.crime_data.violent_crime))
            )
        fig = threed_bar_chart(values,"Population Density","Per-Capita Income", "Violent Crimes")
        canvas=FigureCanvas(fig)
        response=HttpResponse(content_type='image/png')
        canvas.print_png(response)

        safe_set_cache(cache_key,response,86400)
        
    return response
Ejemplo n.º 19
0
    def handle(self, *args, **options):
        usage = 'Required arguments: email password new_password'
        if len(args) != 3:
            raise CommandError(usage)

        email, curr, new = args
        Mailbox = get_model(MAILS_VIRTUAL_MAILBOX.split(".")[0],
                            MAILS_VIRTUAL_MAILBOX.split(".")[1])
        MailDomain = get_model(MAILS_VIRTUAL_MAILDOMAIN.split(".")[0],
                            MAILS_VIRTUAL_MAILDOMAIN.split(".")[1])
        try:
            user = Mailbox.get_from_email(email)
        except ValidationError:
            raise CommandError('Improperly formatted email address.')
        except MailDomain.DoesNotExist:
            raise CommandError('Domain does not exist.')
        except Mailbox.DoesNotExist:
            raise CommandError('Username does not exist.')

        authorized = user.check_password(curr)
        if not authorized:
            raise CommandError('Incorrect password.')

        user.set_password(new)
        user.save()
        self.stdout.write('Success.\n')
Ejemplo n.º 20
0
    def __new__(cls, name, bases, attrs):
        # If this isn't a subclass of Model, don't do anything special.
        try:
            parents = [b for b in bases if issubclass(b, Model)]
            if not parents:
                return super(ModelBase, cls).__new__(cls, name, bases, attrs)
        except NameError:
            # 'Model' isn't defined yet, meaning we're looking at Django's own
            # Model class, defined below.
            return super(ModelBase, cls).__new__(cls, name, bases, attrs)

        # Create the class.
        new_class = type.__new__(cls, name, bases, {'__module__': attrs.pop('__module__')})
        new_class.add_to_class('_meta', Options(attrs.pop('Meta', None)))
        new_class.add_to_class('DoesNotExist', types.ClassType('DoesNotExist', (ObjectDoesNotExist,), {}))
        new_class.add_to_class('MultipleObjectsReturned',
            types.ClassType('MultipleObjectsReturned', (MultipleObjectsReturned, ), {}))

        # Build complete list of parents
        for base in parents:
            # Things without _meta aren't functional models, so they're
            # uninteresting parents.
            if hasattr(base, '_meta'):
                new_class._meta.parents.append(base)
                new_class._meta.parents.extend(base._meta.parents)


        if getattr(new_class._meta, 'app_label', None) is None:
            # Figure out the app_label by looking one level up.
            # For 'django.contrib.sites.models', this would be 'sites'.
            model_module = sys.modules[new_class.__module__]
            new_class._meta.app_label = model_module.__name__.split('.')[-2]

        # Bail out early if we have already created this class.
        m = get_model(new_class._meta.app_label, name, False)
        if m is not None:
            return m

        # Add all attributes to the class.
        for obj_name, obj in attrs.items():
            new_class.add_to_class(obj_name, obj)

        # Add Fields inherited from parents
        for parent in new_class._meta.parents:
            for field in parent._meta.fields:
                # Only add parent fields if they aren't defined for this class.
                try:
                    new_class._meta.get_field(field.name)
                except FieldDoesNotExist:
                    field.contribute_to_class(new_class, field.name)

        new_class._prepare()

        register_models(new_class._meta.app_label, new_class)
        # Because of the way imports happen (recursively), we may or may not be
        # the first class for this model to register with the framework. There
        # should only be one class for each model, so we must always return the
        # registered version.
        return get_model(new_class._meta.app_label, name, False)
Ejemplo n.º 21
0
    def test_builder(self):
        users = get_model('main', 'users')
        self.assertTrue(users)
        rooms = get_model('main', 'rooms')
        self.assertTrue(rooms)

        rooms = get_model('main', 'room')
        self.assertFalse(rooms)
Ejemplo n.º 22
0
 def delete(self, *args, **kwargs):
     DynamicInterface = get_model('cyder', 'dynamicinterface')
     for interface in DynamicInterface.objects.filter(system=self):
         interface.delete(delete_system=False, commit=False)
     StaticInterface = get_model('cyder', 'staticinterface')
     for interface in StaticInterface.objects.filter(system=self):
         interface.delete(delete_system=False, commit=False)
     super(System, self).delete(*args, **kwargs)
Ejemplo n.º 23
0
 def set_actor(self, user, sender, instance, **kwargs):
     try:
         app_label, model_name = settings.AUTH_USER_MODEL.split('.')
         auth_user_model = get_model(app_label, model_name)
     except:
         auth_user_model = get_model('auth', 'user')
     if sender == LogEntry and isinstance(user, auth_user_model) and instance.actor is None:
         instance.actor = user
Ejemplo n.º 24
0
def update_related_fields(instance, related_fields, data):
    """
    Function used to create/update/delete the related fields when updating an existing object.

    Args:
        instance (object): The object whose related fields are going to be created/updated/deleted
        related_fields (dict): Dict containing information about the related fields
        data (dict): Dict containing the actual data for the related fields
    """
    for field in related_fields:
        # Pop items here so setattr() works
        for item_data in data.pop(field['data_string'], {}):
            # In case something went wrong in the front end and an object with
            # the is_deleted flag wasn't removed we set the object to an empty dict.
            # So just to be sure we check for empty data.
            if not item_data:
                continue

            # Convert from OrderedDict to regular dict
            item_data = dict(item_data)

            # Remove is_deleted key from dict (so update/create don't give errors)
            is_deleted = item_data.pop('is_deleted', False)

            if 'id' in item_data:
                # ID is set, so the object exists. Get that object.
                # Note that this isn't a single object but a QuerySet.
                # This is because passing a dict to the .update only works on a QuerySet.
                field_name = field['data_string']
                item_obj = getattr(instance, field_name).filter(pk=item_data['id'])

                # If the related field was marked as deleted, delete it
                if is_deleted:
                    item_obj.delete()
                else:
                    # Otherwise update the object
                    item_obj.update(**item_data)
            else:
                # ID wasn't given, so:
                # 1. Get the model
                # 2. Get the related field set
                # 3. Create an new object from the model and add it to the set

                # Websites are different than the other related fields.
                # For now just have it as an edge case in this function.
                # In the future we might want to change how websites are setup.
                if field['model'] == 'Website':
                    model = get_model('accounts', field['model'])

                    # Websites aren't added to a set, but are given an account
                    item_data.update({
                        'account': instance
                    })
                    model.objects.create(**item_data)
                else:
                    model = get_model('utils', field['model'])
                    field_name = field['data_string']
                    getattr(instance, field_name).add(model.objects.create(**item_data))
Ejemplo n.º 25
0
 def _disable_memberships(cls, user):
     """
     Set all membership of given user to
     MemberStatusField.STATUS_MEMBER_BROKEN
     :param user:
     :return:
     """
     get_model('accounts', 'Member').objects.filter(user=user).update(
         status=MemberStatusField.STATUS_MEMBER_BROKEN)
Ejemplo n.º 26
0
 def filter_by_ctnr(ctnr, objects=None):
     objects = objects or System.objects
     DynamicInterface = get_model('cyder', 'dynamicinterface')
     StaticInterface = get_model('cyder', 'staticinterface')
     dynamic_query = DynamicInterface.objects.filter(
         ctnr=ctnr).values_list('system')
     static_query = StaticInterface.objects.filter(
         ctnr=ctnr).values_list('system')
     return objects.filter(Q(id__in=static_query) | Q(id__in=dynamic_query))
Ejemplo n.º 27
0
def delete_model(request, modelname, id):
    if request.method == 'POST':
        Model = get_model('admin_center', modelname)
        if not Model:
            Model = get_model('mainsite', modelname)
        if not Model:
            raise Http404
        model = Model.objects.get(id=id)
        model.delete()
    return HttpResponse('')
Ejemplo n.º 28
0
def add_view_count(id):
    try:
        get_model('vehicle', 'car').objects.filter(
            pk=id).update(view_count=F('view_count') + 1)
        transaction.commit()
    except Exception as e:
        transaction.rollback()
        logging.error(str(e))
    finally:
        pass
Ejemplo n.º 29
0
def update_watchers_on_membership_post_delete(sender, instance, using, **kwargs):
    models = [get_model("userstories", "UserStory"),
              get_model("tasks", "Task"),
              get_model("issues", "Issue")]

    # `user_id` is used beacuse in some momments
    # instance.user can contain pointer to now
    # removed object from a database.
    for model in models:
        model.watchers.through.objects.filter(user_id=instance.user_id).delete()
Ejemplo n.º 30
0
def send_added_to_bucket(bucket_membership_id):
    BucketMembership = get_model('buckets', 'BucketMembership')
    bucket_membership = BucketMembership.objects.get(id = bucket_membership_id)

    bucket = bucket_membership.bucket
    composition = bucket_membership.composition
    target_user = bucket.owner

    to_user = []

    composition_owner = composition.uploader

    MailOptions = get_model('accounts', 'MailOptions')
    owner_mail_options = MailOptions.objects.get(user=composition_owner)

    if (composition_owner.is_active  and not (target_user.id == composition_owner.id) and owner_mail_options.to_bucket):
        to_user.append(composition_owner.email)

    composition_artist = composition.artist
    artist_mail_options = MailOptions.objects.get(user=composition_artist)

    if composition_artist.is_active and not(composition_owner == composition_artist) and not (target_user.id == composition_artist.id) and artist_mail_options.to_bucket:
        to_user.append(composition_artist.email)

    if not to_user:
        return 'send_added_to_bucket: Counld not find valid recepient for bucket_membership: {0}'.format(bucket_membership.id)

    to = to_user
    subject = target_user.name + " added artwork " + composition.title + " to series " + bucket.name
    from_email = 'ThirdDime <*****@*****.**>'

    ctx = {
        'target_name': target_user.name,
        'target_slug': target_user.slug,
        'target_picture': target_user.picture.url,
        'art_name': composition.title,
        'art_slug': composition.slug,
        'series_name': bucket.name,
        'series_slug': bucket.slug,
        'series_owner_slug': bucket.owner.slug,
    }

    message = get_template('mails/buckets/to_bucket.html').render(Context(ctx))
    msg = EmailMessage(subject, message, to=to, from_email=from_email)
    msg.content_subtype = 'html'

    count = 1
    while count:
        try:
            msg.send(fail_silently=False)
            break;
        except:
            if (count > 3):
                raise
            count += count
Ejemplo n.º 31
0
    def _process_results(self,
                         raw_page,
                         highlight=False,
                         query_string='',
                         spelling_query=None,
                         result_class=None):
        if not self.site:
            from haystack import site
        else:
            site = self.site

        results = []

        # It's important to grab the hits first before slicing. Otherwise, this
        # can cause pagination failures.
        hits = len(raw_page)

        if result_class is None:
            result_class = SearchResult

        facets = {}
        spelling_suggestion = None
        indexed_models = site.get_indexed_models()

        for doc_offset, raw_result in enumerate(raw_page):
            score = raw_page.score(doc_offset) or 0
            app_label, model_name = raw_result[DJANGO_CT].split('.')
            additional_fields = {}
            model = get_model(app_label, model_name)

            if model and model in indexed_models:
                for key, value in raw_result.items():
                    index = site.get_index(model)
                    string_key = str(key)

                    if string_key in index.fields and hasattr(
                            index.fields[string_key], 'convert'):
                        # Special-cased due to the nature of KEYWORD fields.
                        if index.fields[string_key].is_multivalued:
                            if value is None or len(value) is 0:
                                additional_fields[string_key] = []
                            else:
                                additional_fields[string_key] = value.split(
                                    ',')
                        else:
                            additional_fields[string_key] = index.fields[
                                string_key].convert(value)
                    else:
                        additional_fields[string_key] = self._to_python(value)

                del (additional_fields[DJANGO_CT])
                del (additional_fields[DJANGO_ID])

                if highlight:
                    from whoosh import analysis
                    from whoosh.highlight import highlight, ContextFragmenter, UppercaseFormatter
                    sa = analysis.StemmingAnalyzer()
                    terms = [
                        term.replace('*', '') for term in query_string.split()
                    ]

                    additional_fields['highlighted'] = {
                        self.content_field_name: [
                            highlight(
                                additional_fields.get(self.content_field_name),
                                terms, sa, ContextFragmenter(terms),
                                UppercaseFormatter())
                        ],
                    }

                result = result_class(app_label,
                                      model_name,
                                      raw_result[DJANGO_ID],
                                      score,
                                      searchsite=self.site,
                                      **additional_fields)
                results.append(result)
            else:
                hits -= 1

        if getattr(settings, 'HAYSTACK_INCLUDE_SPELLING', False):
            if spelling_query:
                spelling_suggestion = self.create_spelling_suggestion(
                    spelling_query)
            else:
                spelling_suggestion = self.create_spelling_suggestion(
                    query_string)

        return {
            'results': results,
            'hits': hits,
            'facets': facets,
            'spelling_suggestion': spelling_suggestion,
        }
    def _process_results(self, raw_results, highlight=False,
                         result_class=None, distance_point=None,
                         geo_sort=False):
        from haystack import connections
        results = []
        hits = raw_results.get('hits', {}).get('total', 0)
        facets = {}
        spelling_suggestion = None

        if result_class is None:
            result_class = SearchResult

        if self.include_spelling and 'suggest' in raw_results:
            raw_suggest = raw_results['suggest']['suggest']
            spelling_suggestion = ' '.join([word['text'] if len(word['options']) == 0 else word['options'][0]['text'] for word in raw_suggest])

        if 'facets' in raw_results:
            facets = {
                'fields': {},
                'dates': {},
                'queries': {},
            }

            for facet_fieldname, facet_info in raw_results['facets'].items():
                if facet_info.get('_type', 'terms') == 'terms':
                    facets['fields'][facet_fieldname] = [(individual['term'], individual['count']) for individual in facet_info['terms']]
                elif facet_info.get('_type', 'terms') == 'date_histogram':
                    # Elasticsearch provides UTC timestamps with an extra three
                    # decimals of precision, which datetime barfs on.
                    facets['dates'][facet_fieldname] = [(datetime.datetime.utcfromtimestamp(individual['time'] / 1000), individual['count']) for individual in facet_info['entries']]
                elif facet_info.get('_type', 'terms') == 'query':
                    facets['queries'][facet_fieldname] = facet_info['count']

        unified_index = connections[self.connection_alias].get_unified_index()
        indexed_models = unified_index.get_indexed_models()
        content_field = unified_index.document_field

        for raw_result in raw_results.get('hits', {}).get('hits', []):
            source = raw_result['_source']
            app_label, model_name = source[DJANGO_CT].split('.')
            additional_fields = {}
            model = get_model(app_label, model_name)

            if model and model in indexed_models:
                for key, value in source.items():
                    index = unified_index.get_index(model)
                    string_key = str(key)

                    if string_key in index.fields and hasattr(index.fields[string_key], 'convert'):
                        additional_fields[string_key] = index.fields[string_key].convert(value)
                    else:
                        additional_fields[string_key] = self._to_python(value)

                del(additional_fields[DJANGO_CT])
                del(additional_fields[DJANGO_ID])

                if 'highlight' in raw_result:
                    additional_fields['highlighted'] = raw_result['highlight'].get(content_field, '')

                if distance_point:
                    additional_fields['_point_of_origin'] = distance_point

                    if geo_sort and raw_result.get('sort'):
                        from haystack.utils.geo import Distance
                        additional_fields['_distance'] = Distance(km=float(raw_result['sort'][0]))
                    else:
                        additional_fields['_distance'] = None

                result = result_class(app_label, model_name, source[DJANGO_ID], raw_result['_score'], **additional_fields)
                results.append(result)
            else:
                hits -= 1

        return {
            'results': results,
            'hits': hits,
            'facets': facets,
            'spelling_suggestion': spelling_suggestion,
        }
Ejemplo n.º 33
0
def ext_pillar(
        minion_id,  # pylint: disable=W0613
        pillar,  # pylint: disable=W0613
        pillar_name,
        project_path,
        settings_module,
        django_app,
        env=None,
        env_file=None,
        *args,  # pylint: disable=W0613
        **kwargs):  # pylint: disable=W0613
    '''
    Connect to a Django database through the ORM and retrieve model fields

    :type pillar_name: str
    :param pillar_name: The name of the pillar to be returned

    :type project_path: str
    :param project_path: The full path to your Django project (the directory
        manage.py is in)

    :type settings_module: str
    :param settings_module: The settings module for your project. This can be
        found in your manage.py file

    :type django_app: str
    :param django_app: A dictionary containing your apps, models, and fields

    :type env: str
    :param env: The full path to the virtualenv for your Django project

    :type env_file: str
    :param env_file: An optional bash file that sets up your environment. The
        file is run in a subprocess and the changed variables are then added
    '''

    if not os.path.isdir(project_path):
        log.error(
            'Django project dir: {0!r} not a directory!'.format(project_path))
        return {}
    if HAS_VIRTUALENV and env is not None and os.path.isdir(env):
        for path in virtualenv.path_locations(env):
            if not os.path.isdir(path):
                log.error('Virtualenv {0} not a directory!'.format(path))
                return {}
        # load the virtualenv first
        sys.path.insert(
            0,
            os.path.join(virtualenv.path_locations(env)[1], 'site-packages'))

    # load the django project
    sys.path.append(project_path)

    os.environ['DJANGO_SETTINGS_MODULE'] = settings_module

    if env_file is not None:
        import subprocess

        base_env = {}
        proc = subprocess.Popen(['bash', '-c', 'env'], stdout=subprocess.PIPE)
        for line in proc.stdout:
            (key, _, value) = salt.utils.to_str(line).partition('=')
            base_env[key] = value

        command = ['bash', '-c', 'source {0} && env'.format(env_file)]
        proc = subprocess.Popen(command, stdout=subprocess.PIPE)

        for line in proc.stdout:
            (key, _, value) = salt.utils.to_str(line).partition('=')
            # only add a key if it is different or doesn't already exist
            if key not in base_env or base_env[key] != value:
                os.environ[key] = value.rstrip('\n')
                log.debug('Adding {0} = {1} to Django environment'.format(
                    key, value.rstrip('\n')))

    try:
        from django.db.models.loading import get_model

        django_pillar = {}

        for proj_app, models in six.iteritems(django_app):
            _, _, app = proj_app.rpartition('.')
            django_pillar[app] = {}
            for model_name, model_meta in six.iteritems(models):
                model_orm = get_model(app, model_name)
                if model_orm is None:
                    raise salt.exceptions.SaltException(
                        "Django model '{0}' not found in app '{1}'.".format(
                            app, model_name))

                pillar_for_model = django_pillar[app][model_orm.__name__] = {}

                name_field = model_meta['name']
                fields = model_meta['fields']

                if 'filter' in model_meta:
                    qs = (model_orm.objects.filter(
                        **model_meta['filter']).values(*fields))
                else:
                    qs = model_orm.objects.values(*fields)

                for model in qs:
                    # Check that the human-friendly name given is valid (will
                    # be able to pick up a value from the query) and unique
                    # (since we're using it as the key in a dictionary)
                    if name_field not in model:
                        raise salt.exceptions.SaltException(
                            "Name '{0}' not found in returned fields.".format(
                                name_field))

                    if model[name_field] in pillar_for_model:
                        raise salt.exceptions.SaltException(
                            "Value for '{0}' is not unique: {0}".format(
                                model[name_field]))

                    pillar_for_model[model[name_field]] = model

        return {pillar_name: django_pillar}
    except ImportError as e:
        log.error('Failed to import library: {0}'.format(str(e)))
        return {}
    except Exception as e:
        log.error('Failed on Error: {0}'.format(str(e)))
        log.debug('django_orm traceback', exc_info=True)
        return {}
Ejemplo n.º 34
0
def get_model_by_name(name):

    return get_model(*name.split('.',1))
Ejemplo n.º 35
0
    def _process_results(self,
                         raw_results,
                         highlight=False,
                         result_class=None,
                         distance_point=None):
        results = []
        hits = raw_results.hits
        facets = {}
        stats = {}
        spelling_suggestion = None

        if result_class is None:
            result_class = SearchResult

        if hasattr(raw_results, 'stats'):
            stats = raw_results.stats.get('stats_fields', {})

        if hasattr(raw_results, 'facets'):
            facets = {
                'fields': raw_results.facets.get('facet_fields', {}),
                'dates': raw_results.facets.get('facet_dates', {}),
                'queries': raw_results.facets.get('facet_queries', {}),
            }

            for key in ['fields']:
                for facet_field in facets[key]:
                    # Convert to a two-tuple, as Solr's json format returns a list of
                    # pairs.
                    facets[key][facet_field] = list(
                        zip(facets[key][facet_field][::2],
                            facets[key][facet_field][1::2]))

        if self.include_spelling is True:
            if hasattr(raw_results, 'spellcheck'):
                if len(raw_results.spellcheck.get('suggestions', [])):
                    # For some reason, it's an array of pairs. Pull off the
                    # collated result from the end.
                    spelling_suggestion = raw_results.spellcheck.get(
                        'suggestions')[-1]

        unified_index = connections[self.connection_alias].get_unified_index()
        indexed_models = unified_index.get_indexed_models()

        for raw_result in raw_results.docs:
            app_label, model_name = raw_result[DJANGO_CT].split('.')
            additional_fields = {}
            model = get_model(app_label, model_name)

            if model and model in indexed_models:
                for key, value in raw_result.items():
                    index = unified_index.get_index(model)
                    string_key = str(key)

                    if string_key in index.fields and hasattr(
                            index.fields[string_key], 'convert'):
                        additional_fields[string_key] = index.fields[
                            string_key].convert(value)
                    else:
                        additional_fields[string_key] = custom_to_python(
                            value, self.conn._to_python)

                del (additional_fields[DJANGO_CT])
                del (additional_fields[DJANGO_ID])
                del (additional_fields['score'])

                if raw_result[ID] in getattr(raw_results, 'highlighting', {}):
                    additional_fields[
                        'highlighted'] = raw_results.highlighting[
                            raw_result[ID]]

                if distance_point:
                    additional_fields['_point_of_origin'] = distance_point

                    if raw_result.get('__dist__'):
                        from haystack.utils.geo import Distance
                        additional_fields['_distance'] = Distance(
                            km=float(raw_result['__dist__']))
                    else:
                        additional_fields['_distance'] = None

                result = result_class(app_label, model_name,
                                      raw_result[DJANGO_ID],
                                      raw_result['score'], **additional_fields)
                results.append(result)
            else:
                hits -= 1

        return {
            'results': results,
            'hits': hits,
            'stats': stats,
            'facets': facets,
            'spelling_suggestion': spelling_suggestion,
        }
Ejemplo n.º 36
0
def get_tenant_model():
    return get_model(settings.TENANT_MODEL)
Ejemplo n.º 37
0
 def _get_listing(self, publishable, score):
     Listing = get_model('core', 'listing')
     publish_from = from_timestamp(score)
     return Listing(publishable=publishable,
                    category=publishable.category,
                    publish_from=publish_from)
Ejemplo n.º 38
0
 def test_get_model_with_not_installed(self):
     self.assertEqual(
         get_model("not_installed",
                   "NotInstalledModel",
                   only_installed=False),
         self.not_installed_module.NotInstalledModel)
Ejemplo n.º 39
0
def get_wepay_model(obj_name):
    model_name = get_wepay_model_name(obj_name)
    if model_name is None:
        return None
    return get_model(*model_name.split('.'))
Ejemplo n.º 40
0
 def test_get_model_only_returns_installed_models(self):
     self.assertEqual(get_model("not_installed", "NotInstalledModel"), None)
Ejemplo n.º 41
0
def get_tenant_domain_model():
    return get_model(settings.TENANT_DOMAIN_MODEL)
Ejemplo n.º 42
0
 def get_queryset(self):
     model = get_model('miscitems', 'Material')
     self.items = get_list_or_404(model)
     return self.items
Ejemplo n.º 43
0
class DeployAPI(BaseAPI):
    
    model = get_model('cannula', 'deployment')
    
    def _create(self, project, user, oldrev, newrev, conf_oldrev, conf_newrev):
        self.model.objects.create(project=project, user=user, oldrev=oldrev,
            newrev=newrev, conf_oldrev=conf_oldrev, conf_newrev=conf_newrev)
    
    def deploy(self, project, user, oldrev='old', newrev='new'):
        user = api.users.get(user)
        project = api.projects.get(project)
        if not os.path.isfile(project.appconfig):
            raise ApiError("Project missing app.yaml file!")
        
        # Attempt to get an exclusive lock on the project
        # file. A way to ensure only one process can deploy
        # at any single time. This is hard because deployment is
        # triggered by a git push (which is just an ssh connection)
        with DeployLock(project, user):
            with open(project.appconfig) as f:
                
                # Store the configuration for this project in git repo
                # so that we can roll back to previous states
                conf_dir = Git(project.conf_dir)
                
                if not os.path.isdir(project.conf_dir):
                    os.makedirs(project.conf_dir)
                    conf_dir.init()
                    # Add an initial commit, just to make a rollback point.
                    open(project.deployconfig, 'a')
                    conf_dir.add_all()
                    conf_dir.commit("Initial Commit")
                
                # Copy the project app.yaml to the conf_dir
                shutil.copy(project.appconfig, project.deployconfig)
                
                # read in the application configuration
                app = yaml.load(f.read())
                
                # setup any runtime specific things here
                try:
                    runtime = import_object(app.get('runtime'))
                except ImportError:
                    raise ApiError("Unsupported runtime!")
                # runtime bootstrap, setup project environment here
                runtime.bootstrap(project, app)    
                    
            
                # Simple counter to make unique names for each handler
                # and keep them in order
                handler_position = 0
                sections = []
                for handler in app.get('handlers', []):
                    if handler.get('worker'):
                        # Setup worker
                        name = '%s_%d' % (project.name, handler_position)
                        # defaults are special, they reference another
                        # section in the app.yaml
                        defaults = handler.pop('defaults', None)
                        if defaults:
                            handler_defaults = app.get(defaults, {})
                            handler.update(handler_defaults)
                        handle = Handler(name, project, **handler)
                        # write out bash start up scripts
                        handle.write_startup_script()
                        # add handler to vhost_sections
                        sections.append(handle)
                        handler_position += 1
                    else:
                        # Just pass the dictionary to the proxy vhosts
                        sections.append(handler)
                
                # Write out the proxy file to serve this app
                ctx = {
                    'sections': sections,
                    'domain': app.get('domain', 'localhost'),
                    'runtime': app.get('runtime', 'python'),
                    'port': app.get('port', 80),
                    'project_conf_dir': project.conf_dir,
                    'conf_dir': os.path.join(conf.CANNULA_BASE, 'config'),
                    'project': project,
                }
                api.proxy.write_vhost_conf(project, ctx)
                api.proc.write_project_conf(project, ctx)
                
                # Check if any files changed and check if still valid
                conf_dir.add_all()
                _, changed = conf_dir.status()
                logging.debug(changed)
                if re.search('vhost.conf', changed):
                    # Vhost file is either new or changed which will require 
                    # our proxy server to reload its configuration files.
                    try:
                        api.proxy.restart()
                    except:
                        logging.exception("Error restarting proxy")
                        conf_dir.reset()
                        raise ApiError("Deployment failed")
                if re.search('supervisor.conf', changed):
                    try:
                        api.proc.reread()
                    except:
                        logging.exception("Error reading supervisor configs")
                        conf_dir.reset()
                        raise ApiError("Deployment failed")
                
                # Add the project
                api.proc.reread(stderr=True)
                api.proc.add_project(project.name)
                    
                # Restart the project
                try:
                    api.proc.restart(project.name, stderr=True)
                except:
                    logging.exception("Error restarting project")
                    conf_dir.reset()
                    raise ApiError("Deployment failed")
                # Current revision of conf directory
                conf_oldrev = conf_dir.head()
                if changed:
                    # Commit config changes
                    conf_dir.commit("Configuration: %s" % datetime.datetime.now().ctime())
                
                # new revision of conf directory
                conf_newrev = conf_dir.head()
                if oldrev is None:
                    oldrev = "Initial Commit"
                self._create(project, user, oldrev, newrev, conf_oldrev, conf_newrev)     
Ejemplo n.º 44
0
 def _get_listing(self, publishable, score):
     Listing = get_model('core', 'listing')
     return Listing(publishable=publishable, category=publishable.category)
Ejemplo n.º 45
0
    def can_admin(self, user):
        if self.backlog_id:
            return user.is_staff or self.backlog.can_admin(user)
        elif self.project_id:
            return user.is_staff or self.project.can_admin(user)
        else:
            return False


# Enhance User model to add notifications
def user_notification_count(self):
    return AuthorizationAssociation.objects.filter(
        user=self,
        is_active=False
    ).count()
get_model(*User.split('.', 1)).notification_count = user_notification_count


class Event(models.Model):
    user = models.ForeignKey(User, verbose_name=_("User"),
                             related_name="events")
    when = models.DateTimeField(_("When"), auto_now_add=True)
    project = models.ForeignKey(Project, verbose_name=_("Project"),
                                related_name="events", null=True,
                                on_delete=models.SET_NULL)
    story = models.ForeignKey(UserStory, verbose_name=_("Story"),
                              blank=True, null=True, related_name="events",
                              on_delete=models.SET_NULL)
    backlog = models.ForeignKey(Backlog, verbose_name=_("Backlog"),
                                blank=True, null=True, related_name="events",
                                on_delete=models.SET_NULL)
Ejemplo n.º 46
0
def tuple_to_model(t):
    return get_model(t[0], t[1])
Ejemplo n.º 47
0
def get_results(query_string, model_name, fields):
    query_obj = get_query(query_string, fields)
    model = get_model('webapp', model_name)
    if model is None:
        return []
    return [] if query_obj is None else model.objects.filter(query_obj)
Ejemplo n.º 48
0
 def get_queryset(self):
     model = get_model('miscitems', self.model)
     self.item = get_object_or_404(model,
                                   name_slug=self.kwargs['name_slug'])
     return self.item
Ejemplo n.º 49
0
def ListingHandlerClass():
    return get_model('core', 'Listing').objects.get_listing_handler(
        core_settings.REDIS_LISTING_HANDLER)
Ejemplo n.º 50
0
def get_cached_objects(pks, model=None, timeout=CACHE_TIMEOUT, missing=RAISE):
    """
    Return a list of objects with given PKs using cache.

    Params:
        pks - list of Primary Key values to look up or list of content_type_id, pk tuples
        model - ContentType instance representing the model's class or the model class itself
        timeout - TTL for the items in cache, defaults to CACHE_TIMEOUT

    Throws:
        model.DoesNotExist is propagated from content_type.get_object_for_this_type
    """
    if model is not None:
        if not isinstance(model, ContentType):
            model = ContentType.objects.get_for_model(model)
        pks = [(model, pk) for pk in pks]
    else:
        pks = [(ContentType.objects.get_for_id(ct_id), pk) for (ct_id, pk) in pks]

    keys = [_get_key(KEY_PREFIX, model, pk=pk) for (model, pk) in pks]

    cached = cache.get_many(keys)

    # keys not in cache
    keys_to_set = set(keys) - set(cached.keys())
    if keys_to_set:
        # build lookup to get model and pks from the key
        lookup = dict(zip(keys, pks))

        to_get = {}
        # group lookups by CT so we can do in_bulk
        for k in keys_to_set:
            ct, pk = lookup[k]
            to_get.setdefault(ct, {})[int(pk)] = k

        # take out all the publishables
        publishable_ct = ContentType.objects.get_for_model(get_model('core', 'publishable'))
        if publishable_ct in to_get:
            publishable_keys = to_get.pop(publishable_ct)
            models = publishable_ct.model_class()._default_manager.values('content_type_id', 'id').filter(id__in=publishable_keys.keys())
            for m in models:
                ct = ContentType.objects.get_for_id(m['content_type_id'])
                pk = m['id']
                # and put them back as their native content_type
                to_get.setdefault(ct, {})[pk] = publishable_keys[pk]

        to_set = {}
        # retrieve all the models from DB
        for ct, vals in to_get.items():
            models = ct.model_class()._default_manager.in_bulk(vals.keys())
            for pk, m in models.items():
                k = vals[pk]
                cached[k] = to_set[k] = m

        if not isinstance(cache, DummyCache):
            # write them into cache
            cache.set_many(to_set, timeout=timeout)

    out = []
    for k in keys:
        try:
            out.append(cached[k])
        except KeyError:
            if missing == NONE:
                out.append(None)
            elif missing == SKIP:
                pass
            elif missing == RAISE:
                ct = ContentType.objects.get_for_id(int(k.split(':')[1]))
                raise ct.model_class().DoesNotExist(
                    '%s matching query does not exist.' % ct.model_class()._meta.object_name)
    return out
Ejemplo n.º 51
0
def get_tenant_model():
    return get_model(*settings.TENANT_MODEL.split("."))
Ejemplo n.º 52
0
 def test_get_model(self):
     self.assertEqual(get_model('tests', 'poll'), Poll)
     self.assertEqual(get_model('tests', 'historicalpoll'), HistoricalPoll)
Ejemplo n.º 53
0
def get_sms_template_model():
    return get_model(*settings.TEMPLATE_MODEL.split('.'))
Ejemplo n.º 54
0
import datetime

from django.contrib import messages
from django.core.urlresolvers import reverse
from django.db.models.loading import get_model
from django.http import HttpResponseRedirect
from django.utils.translation import ugettext_lazy as _
from django.views.generic import (ListView, FormView, DetailView, DeleteView)

from oscar.core.loading import get_class

VoucherForm = get_class('dashboard.vouchers.forms', 'VoucherForm')
VoucherSearchForm = get_class('dashboard.vouchers.forms', 'VoucherSearchForm')
Voucher = get_model('voucher', 'Voucher')
ConditionalOffer = get_model('offer', 'ConditionalOffer')
Benefit = get_model('offer', 'Benefit')
Condition = get_model('offer', 'Condition')
OrderDiscount = get_model('order', 'OrderDiscount')


class VoucherListView(ListView):
    model = Voucher
    context_object_name = 'vouchers'
    template_name = 'dashboard/vouchers/voucher_list.html'
    form_class = VoucherSearchForm
    description_template = _("%(main_filter)s %(name_filter)s %(code_filter)s")

    def get_queryset(self):
        qs = self.model.objects.all().order_by('-date_created')
        self.description_ctx = {
            'main_filter': _('All vouchers'),
Ejemplo n.º 55
0
def get_output_sms_model():
    return get_model(*settings.OUTPUT_SMS_MODEL.split('.'))
Ejemplo n.º 56
0
from django.db.models.loading import get_model
from django.contrib.contenttypes.models import ContentType
from django.contrib.admin.views.decorators import staff_member_required

from accounts.models import VenueAccount, VenueType, Account
from event.models import SingleEvent, FeaturedEvent, Venue
from event.services.featured_service import featured_events_for_region
from event.services import venue_service as event_venue_service, location_service
from venues.forms import VenueAccountForm, NewVenueAccountForm
from .services import social_links_services, venue_service
from .forms import VenueForm

MAX_SUGGESTIONS = getattr(settings, 'TAGGIT_AUTOSUGGEST_MAX_SUGGESTIONS', 10)

TAG_MODEL = getattr(settings, 'TAGGIT_AUTOSUGGEST_MODEL', ('taggit', 'Tag'))
TAG_MODEL = get_model(*TAG_MODEL)


def venues(request, *args, **kwargs):
    current_venue_type = int(request.GET.get("venue_type", 0))
    if not current_venue_type \
            and 'extra_params' in kwargs \
                and 'venue_type' in kwargs['extra_params']:
        try:
            venue_type = VenueType.active_types.get(
                name=kwargs['extra_params']['venue_type'])
        except VenueType.DoesNotExist:
            pass
        else:
            current_venue_type = venue_type.id
Ejemplo n.º 57
0
def get_input_sms_model():
    return get_model(*settings.INPUT_SMS_MODEL.split('.'))
Ejemplo n.º 58
0
from django import forms
from django.db.models.loading import get_model
from django.utils.translation import ugettext_lazy as _

from oscar.forms import widgets

Voucher = get_model('voucher', 'Voucher')
Benefit = get_model('offer', 'Benefit')
Range = get_model('offer', 'Range')


class VoucherForm(forms.Form):
    """
    A specialised form for creating a voucher and offer
    model.
    """
    name = forms.CharField(label=_("Name"))
    code = forms.CharField(label=_("Code"))

    start_date = forms.DateField(label=_("Start date"),
                                 widget=widgets.DatePickerInput())
    end_date = forms.DateField(label=_("End date"),
                               widget=widgets.DatePickerInput())
    usage = forms.ChoiceField(choices=Voucher.USAGE_CHOICES, label=_("Usage"))

    benefit_range = forms.ModelChoiceField(
        label=_('Which products get a discount?'),
        queryset=Range.objects.all(),
    )
    type_choices = (
        (Benefit.PERCENTAGE, _('Percentage off of products in range')),
Ejemplo n.º 59
0
def manage_objects(request, model_name):
    # logger.info("Welcome to GLUEBOX api")
    return Epoxy(request).queryset(get_model("glue",
                                             model_name).objects.filter(),
                                   model_name=model_name).json()
Ejemplo n.º 60
0
    def __new__(cls, name, bases, attrs):
        super_new = super(ModelBase, cls).__new__
        parents = [b for b in bases if isinstance(b, ModelBase)]
        if not parents:
            # If this isn't a subclass of Model, don't do anything special.
            return super_new(cls, name, bases, attrs)

        # Create the class.
        module = attrs.pop('__module__')
        new_class = super_new(cls, name, bases, {'__module__': module})
        attr_meta = attrs.pop('Meta', None)
        abstract = getattr(attr_meta, 'abstract', False)
        if not attr_meta:
            meta = getattr(new_class, 'Meta', None)
        else:
            meta = attr_meta
        base_meta = getattr(new_class, '_meta', None)

        if getattr(meta, 'app_label', None) is None:
            # Figure out the app_label by looking one level up.
            # For 'django.contrib.sites.models', this would be 'sites'.
            model_module = sys.modules[new_class.__module__]
            kwargs = {"app_label": model_module.__name__.split('.')[-2]}
        else:
            kwargs = {}

        new_class.add_to_class('_meta', Options(meta, **kwargs))
        if not abstract:
            new_class.add_to_class('DoesNotExist', subclass_exception('DoesNotExist',
                    tuple(x.DoesNotExist
                            for x in parents if hasattr(x, '_meta') and not x._meta.abstract)
                                    or (ObjectDoesNotExist,), module))
            new_class.add_to_class('MultipleObjectsReturned', subclass_exception('MultipleObjectsReturned',
                    tuple(x.MultipleObjectsReturned
                            for x in parents if hasattr(x, '_meta') and not x._meta.abstract)
                                    or (MultipleObjectsReturned,), module))
            if base_meta and not base_meta.abstract:
                # Non-abstract child classes inherit some attributes from their
                # non-abstract parent (unless an ABC comes before it in the
                # method resolution order).
                if not hasattr(meta, 'ordering'):
                    new_class._meta.ordering = base_meta.ordering
                if not hasattr(meta, 'get_latest_by'):
                    new_class._meta.get_latest_by = base_meta.get_latest_by

        is_proxy = new_class._meta.proxy

        if getattr(new_class, '_default_manager', None):
            if not is_proxy:
                # Multi-table inheritance doesn't inherit default manager from
                # parents.
                new_class._default_manager = None
                new_class._base_manager = None
            else:
                # Proxy classes do inherit parent's default manager, if none is
                # set explicitly.
                new_class._default_manager = new_class._default_manager._copy_to_model(new_class)
                new_class._base_manager = new_class._base_manager._copy_to_model(new_class)

        # Bail out early if we have already created this class.
        m = get_model(new_class._meta.app_label, name,
                      seed_cache=False, only_installed=False)
        if m is not None:
            return m

        # Add all attributes to the class.
        for obj_name, obj in attrs.items():
            new_class.add_to_class(obj_name, obj)

        # All the fields of any type declared on this model
        new_fields = new_class._meta.local_fields + \
                     new_class._meta.local_many_to_many + \
                     new_class._meta.virtual_fields
        field_names = set([f.name for f in new_fields])

        # Basic setup for proxy models.
        if is_proxy:
            base = None
            for parent in [cls for cls in parents if hasattr(cls, '_meta')]:
                if parent._meta.abstract:
                    if parent._meta.fields:
                        raise TypeError("Abstract base class containing model fields not permitted for proxy model '%s'." % name)
                    else:
                        continue
                if base is not None:
                    raise TypeError("Proxy model '%s' has more than one non-abstract model base class." % name)
                else:
                    base = parent
            if base is None:
                    raise TypeError("Proxy model '%s' has no non-abstract model base class." % name)
            if (new_class._meta.local_fields or
                    new_class._meta.local_many_to_many):
                raise FieldError("Proxy model '%s' contains model fields." % name)
            new_class._meta.setup_proxy(base)
            new_class._meta.concrete_model = base._meta.concrete_model
        else:
            new_class._meta.concrete_model = new_class

        # Do the appropriate setup for any model parents.
        o2o_map = dict([(f.rel.to, f) for f in new_class._meta.local_fields
                if isinstance(f, OneToOneField)])

        for base in parents:
            original_base = base
            if not hasattr(base, '_meta'):
                # Things without _meta aren't functional models, so they're
                # uninteresting parents.
                continue

            parent_fields = base._meta.local_fields + base._meta.local_many_to_many
            # Check for clashes between locally declared fields and those
            # on the base classes (we cannot handle shadowed fields at the
            # moment).
            for field in parent_fields:
                if field.name in field_names:
                    raise FieldError('Local field %r in class %r clashes '
                                     'with field of similar name from '
                                     'base class %r' %
                                        (field.name, name, base.__name__))
            if not base._meta.abstract:
                # Concrete classes...
                base = base._meta.concrete_model
                if base in o2o_map:
                    field = o2o_map[base]
                elif not is_proxy:
                    attr_name = '%s_ptr' % base._meta.module_name
                    field = OneToOneField(base, name=attr_name,
                            auto_created=True, parent_link=True)
                    new_class.add_to_class(attr_name, field)
                else:
                    field = None
                new_class._meta.parents[base] = field
            else:
                # .. and abstract ones.
                for field in parent_fields:
                    new_class.add_to_class(field.name, copy.deepcopy(field))

                # Pass any non-abstract parent classes onto child.
                new_class._meta.parents.update(base._meta.parents)

            # Inherit managers from the abstract base classes.
            new_class.copy_managers(base._meta.abstract_managers)

            # Proxy models inherit the non-abstract managers from their base,
            # unless they have redefined any of them.
            if is_proxy:
                new_class.copy_managers(original_base._meta.concrete_managers)

            # Inherit virtual fields (like GenericForeignKey) from the parent
            # class
            for field in base._meta.virtual_fields:
                if base._meta.abstract and field.name in field_names:
                    raise FieldError('Local field %r in class %r clashes '\
                                     'with field of similar name from '\
                                     'abstract base class %r' % \
                                        (field.name, name, base.__name__))
                new_class.add_to_class(field.name, copy.deepcopy(field))

        if abstract:
            # Abstract base models can't be instantiated and don't appear in
            # the list of models for an app. We do the final setup for them a
            # little differently from normal models.
            attr_meta.abstract = False
            new_class.Meta = attr_meta
            return new_class

        new_class._prepare()
        register_models(new_class._meta.app_label, new_class)

        # Because of the way imports happen (recursively), we may or may not be
        # the first time this model tries to register with the framework. There
        # should only be one class for each model, so we always return the
        # registered version.
        return get_model(new_class._meta.app_label, name,
                         seed_cache=False, only_installed=False)