示例#1
0
def add_instance(request, model_name):
    def select_model_by_name(name):
        from catalog.admin.utils import get_connected_models
        connected_models = get_connected_models()
        model_list = [item[0].__name__.lower() for item in connected_models]
        try:
            return connected_models[model_list.index(name)][0]
        except ValueError:
            return None

    parent_tree_item = TreeItem.manager.json(request.REQUEST.get('parent', 'root'))

    model_cls = select_model_by_name(model_name)
    if model_cls is None:
        raise Http404

    instance = model_cls(name=u'%s' % model_cls._meta.verbose_name)
    instance.save(save_tree_id=False)

    tree_item = TreeItem(parent=parent_tree_item, content_object=instance)
    tree_item.save()
    
    instance.save()

    return HttpResponseRedirect('/admin/%s/%s/%d/?_popup=1'
        % (instance.__module__.rsplit('.', 2)[-2], model_name, instance.id))
示例#2
0
    def _update_or_create_item(self, **kwds):
        item_options_list = [
            'price', 'wholesale_price', 'quantity', 'barcode',
            'identifier', 'short_description', 'name', 'slug',
        ]
        item_options = {}
        for k, v in kwds.iteritems():
            if k in item_options_list:
                item_options[k] = v
        item_options['slug'] = urlify(kwds['name'])
        
        if kwds['identifier'] in self.data['item_by_identifier']:
            item = self.data['item_by_identifier'][kwds['identifier']]
            for k, v in item_options.iteritems():
                setattr(item, k, v)
            item.save()
 
            self.data['item_by_identifier'].update({item.identifier: item})
            logging.debug('[U] %s' % kwds['name'])
            # True if created
            return False
        else:
            item = Item(**item_options)
            item.save()

            tree_item = TreeItem(parent=kwds['parent'], content_object=item)
            tree_item.save()
            
            self.data['item_by_identifier'].update({item.identifier: item})
            logging.debug('[S] %s' % item.name)
            # True if created
            return True
def insert_in_tree(sender, instance, **kwargs):
    """
    Create TreeItem object after content object created
    """
    created = kwargs.pop('created', False)
    if created:
        tree_item = TreeItem(parent=None, content_object=instance)
        tree_item.save()
    else:
        tree_item = instance.tree.get()
        if tree_item.get_slug() and \
                        instance.full_path() != cache.get(instance.cache_url_key()):
            instance.clear_cache()
示例#4
0
def insert_in_tree(sender, instance, **kwargs):
    """
    Create TreeItem object after content object created
    """
    created = kwargs.pop('created', False)
    if created:
        tree_item = TreeItem(parent=None, content_object=instance)
        tree_item.save()
    else:
        tree_item = instance.tree.get()
        if tree_item.get_slug() and \
                        instance.full_path() != cache.get(instance.cache_url_key()):
            instance.clear_cache()
示例#5
0
    def _get_or_create_section(self, name, parent):
        if name in self.data['section_by_name']:
            return self.data['section_by_name'][name].tree.get()
        else:
            section = Section(name=name, slug=urlify(name))
            section.save()

            section_tree_item = TreeItem(parent=parent, content_object=section)
            section_tree_item.save()

            self.data['section_by_name'].update({section.name: section})

            logging.debug('[S] === %s ===' % section)
            return section_tree_item
示例#6
0
 def clean_slug(self):
     """
     :return: slug if objects with this slug do not exist in this
             level
             else raise validation error
     """
     slug = self.cleaned_data['slug']
     if obj is None:
         node = None
         target = None
         position = 'last-child'
     else:
         node = obj.tree.get()
         target = node
         position = 'left'
     target_id = request.GET.get('target', None)
     copy_id = request.GET.get('copy', None)
     if target_id or copy_id:
         try:
             if target_id:
                 target = TreeItem.objects.get(pk=target_id)
             elif copy_id:
                 target = TreeItem.objects.get(pk=copy_id).parent
         except TreeItem.DoesNotExist:
             pass
         position = 'last-child'
     if not TreeItem.check_slug(target, position, slug, node):
         message = _(u'Slug %(slug)s already exist in this '
                     u'level') % {
                         'slug': self.cleaned_data['slug']
                     }
         raise forms.ValidationError(message)
     return slug
示例#7
0
 def clean_slug(self):
     """
     :return: slug if objects with this slug do not exist in this
             level
             else raise validation error
     """
     slug = self.cleaned_data['slug']
     if obj is None:
         node = None
         target = None
         position = 'last-child'
     else:
         node = obj.tree.get()
         target = node
         position = 'left'
     target_id = request.GET.get('target', None)
     copy_id = request.GET.get('copy', None)
     if target_id or copy_id:
         try:
             if target_id:
                 target = TreeItem.objects.get(pk=target_id)
             elif copy_id:
                 target = TreeItem.objects.get(pk=copy_id).parent
         except TreeItem.DoesNotExist:
             pass
         position = 'last-child'
     if not TreeItem.check_slug(target, position, slug, node):
         message = _(u'Slug %(slug)s already exist in this '
                     u'level') % {'slug': self.cleaned_data['slug']}
         raise forms.ValidationError(message)
     return slug
示例#8
0
    def _get_or_create_section(self, name, parent):
        if name in self.data['section_by_name']:
            return self.data['section_by_name'][name].tree.get()
        else:
            section = Section(
                name=name, slug = urlify(name)
            )
            section.save()

            section_tree_item  = TreeItem(parent=parent, content_object=section)
            section_tree_item.save()

            self.data['section_by_name'].update({section.name: section})
            
            logging.debug('[S] === %s ===' % section)
            return section_tree_item
示例#9
0
    def _update_or_create_item(self, **kwds):
        item_options_list = [
            'price',
            'wholesale_price',
            'quantity',
            'barcode',
            'identifier',
            'short_description',
            'name',
            'slug',
        ]
        item_options = {}
        for k, v in kwds.iteritems():
            if k in item_options_list:
                item_options[k] = v
        item_options['slug'] = urlify(kwds['name'])

        if kwds['identifier'] in self.data['item_by_identifier']:
            item = self.data['item_by_identifier'][kwds['identifier']]
            for k, v in item_options.iteritems():
                setattr(item, k, v)
            item.save()

            self.data['item_by_identifier'].update({item.identifier: item})
            logging.debug('[U] %s' % kwds['name'])
            # True if created
            return False
        else:
            item = Item(**item_options)
            item.save()

            tree_item = TreeItem(parent=kwds['parent'], content_object=item)
            tree_item.save()

            self.data['item_by_identifier'].update({item.identifier: item})
            logging.debug('[S] %s' % item.name)
            # True if created
            return True
示例#10
0
    def move_tree_item(self, request):
        """
        Moves node relative to a given target node as specified
        by position
        :param request:
            request.POST contains item_id, target_id, position
            item_id: id of movable node
            target_id: id of target node
            valid values for position are first-child, last-child, left, right
        :return: JSON data with results of operation
        """
        if request.method == "POST":
            position = request.POST.get('position', None)
            target_id = request.POST.get('target_id', None)
            item_id = request.POST.get('item_id', None)

            if item_id and position and target_id:
                try:
                    node = TreeItem.objects.get(id=item_id)
                    target = TreeItem.objects.get(id=target_id)
                except TreeItem.DoesNotExist:
                    message = _(u'Object does not exist')
                    return JsonResponse({'status': 'error',
                                         'type_message': 'error',
                                         'message': message},
                                        encoder=LazyEncoder,)
                slug = node.get_slug()
                if slug is not None and \
                        not TreeItem.check_slug(target, position,
                                                node.get_slug(), node=node):
                    message = _(u'Invalid move. Slug %(slug)s exist in '
                                u'this level') % {'slug': node.get_slug()}
                    return JsonResponse({
                                        'status': 'error',
                                        'type_message': 'error',
                                        'message': message
                                        },
                                        encoder=LazyEncoder)
                node.move_to(target, position)
                message = _(u'Successful move')
                return JsonResponse({'status': 'OK', 'type_message': 'info',
                                     'message': message}, encoder=LazyEncoder)
        message = _(u'Bad request')
        return JsonResponse({'status': 'error', 'type_message': 'error',
                             'message': message}, encoder=LazyEncoder)
示例#11
0
    def create_item(self, item_params):
        try:
            target_tree_item = TreeItem.objects.get(name=u'Импорт')
        except TreeItem.DoesNotExist:
            target_tree_item = TreeItem(parent_id=None, name=u'Импорт')
            target_tree_item.save()
            target_section = Section(is_meta_item=False)
            target_section.save()
            target_tree_item.section = target_section
            target_tree_item.save()

        new_tree_item = TreeItem(name=item_params['name'][:200],
                                 parent=target_tree_item)
        new_item = Item(
            price=item_params['price'],
            identifier=item_params['identifier'],
            quantity=item_params['quantity'],
        )
        new_tree_item.save()
        new_item.save()
        new_tree_item.item = new_item
        new_tree_item.save()
示例#12
0
    def move_tree_item(self, request):
        """
        Moves node relative to a given target node as specified
        by position
        :param request:
            request.POST contains item_id, target_id, position
            item_id: id of movable node
            target_id: id of target node
            valid values for position are first-child, last-child, left, right
        :return: JSON data with results of operation
        """
        if request.method == "POST":
            position = request.POST.get('position', None)
            target_id = request.POST.get('target_id', None)
            item_id = request.POST.get('item_id', None)

            if item_id and position and target_id:
                try:
                    node = TreeItem.objects.get(id=item_id)
                    target = TreeItem.objects.get(id=target_id)
                except TreeItem.DoesNotExist:
                    message = _(u'Object does not exist')
                    return JsonResponse(
                        {
                            'status': 'error',
                            'type_message': 'error',
                            'message': message
                        },
                        encoder=LazyEncoder,
                    )
                slug = node.get_slug()
                if slug is not None and \
                        not TreeItem.check_slug(target, position,
                                                node.get_slug(), node=node):
                    message = _(u'Invalid move. Slug %(slug)s exist in '
                                u'this level') % {
                                    'slug': node.get_slug()
                                }
                    return JsonResponse(
                        {
                            'status': 'error',
                            'type_message': 'error',
                            'message': message
                        },
                        encoder=LazyEncoder)
                node.move_to(target, position)
                message = _(u'Successful move')
                return JsonResponse(
                    {
                        'status': 'OK',
                        'type_message': 'info',
                        'message': message
                    },
                    encoder=LazyEncoder)
        message = _(u'Bad request')
        return JsonResponse(
            {
                'status': 'error',
                'type_message': 'error',
                'message': message
            },
            encoder=LazyEncoder)
示例#13
0
 def create_item(self, item_params):
     try:
         target_tree_item = TreeItem.objects.get(name=u'Импорт')
     except TreeItem.DoesNotExist:
         target_tree_item = TreeItem(parent_id=None, name=u'Импорт')
         target_tree_item.save()
         target_section = Section(is_meta_item=False)
         target_section.save()
         target_tree_item.section = target_section
         target_tree_item.save()
         
     new_tree_item = TreeItem(name = item_params['name'][:200],
         parent=target_tree_item)
     new_item = Item(
         price = item_params['price'],
         identifier = item_params['identifier'],
         quantity = item_params['quantity'],
     )
     new_tree_item.save()
     new_item.save()
     new_tree_item.item = new_item
     new_tree_item.save()