def main():
    parent_cates = [CATE_RECOMMENDATION]
    parent_cates.extend(cates.keys())
    Category.drop_collection()
    for parent_cate in parent_cates:
        Category.objects.create(title=parent_cate, name=parent_cate,
                create_at=datetime.datetime.utcnow())
Beispiel #2
0
    def post(request, lang, category_id):
        category_model = Category()
        category = category_model.get_by_id(category_id)
        groups = Group.get_all()
        category_count = category.video_set.all().count()
        category_count_en = category.videoen_set.all().count()

        try:
            if category_count == 0 and category_count_en == 0:
                category_model.delete_category(category_id)
                return HttpResponseRedirect(
                    '/{}/admin/categories'.format(lang))

        except:
            pass

        title = category.name_ja

        return TemplateResponse(
            request, 'category.html', {
                'title': title + ' | カテゴリー | FEED App 管理',
                'category': category,
                'groups': groups,
                'form_data': {},
                'error_messages': {
                    'delete': ['invalid']
                },
                'lang': lang,
            })
Beispiel #3
0
class CategoryModelTests(TestCase):
    def setUp(self):
        self.category = CategoryFactory()
        self.my_category = Category(name="my_category")

    def test_should_throw_error_if_category_already_exists(self):
        with self.assertRaises(IntegrityError) as context_message:
            self.my_category.save()
            my_category_1 = Category(name="my_category")
            my_category_1.save()

    def test_should_throw_error_if_name_exceeds_100_character(self):
        with self.assertRaises(DataError) as context_message:
            CategoryFactory(name='Full Metal Havok More Sexy N Intelligent Than Spock And All The Superheroes Combined With Frostnova nova')

    def test_should_throw_error_if_category_order_is_a_negative_value(self):
        with self.assertRaises(IntegrityError) as context_message:
            self.my_category.order = -1
            self.my_category.save()

    def test_absolute_url(self):
        absolute_url = self.category.get_absolute_url()
        self.assertRegexpMatches(absolute_url,'things-we-do')

    def test_str(self):
        self.assertEqual(self.category.__str__(),'Things we do')
Beispiel #4
0
 def create_or_update_categories(self, selector):
     categories = Category.objects.filter(active=True)
     category_by_name = {c.name.lower(): c for c in categories}
     category_by_css = {}
     for option in selector.xpath('//select[@name="category"]/option'):
         category_name = option.extract_first_value_with_xpath('./text()')
         if category_name == '':
             continue
         category_css_name = option.extract_first_value_with_xpath(
             './@value')
         lower_name = category_name.lower()
         if lower_name in category_by_name:
             cat = category_by_name.pop(lower_name)
             if not cat.active:
                 cat.name = category_name.capitalize()
                 cat.active = True
                 cat.save()
                 self.debug_info(
                     'Reactive category {0}'.format(category_name))
         else:
             cat = Category(name=category_name.capitalize(), active=True)
             cat.save()
             self.debug_info(
                 'Create new category {0}'.format(category_name))
         category_by_css[category_css_name] = cat
     self.category_by_css = category_by_css
 def testGetOrCreate2(self):
     category, created = Category.objects.get_or_create(name = 'someblogs2', parent = self.blogs)
     self.assertTrue(created)
     category, created = Category.objects.get_or_create(name = 'someblogs2', parent = self.blogs)
     self.assertFalse(created)
     cat = Category(name = 'someblogs3', parent = self.blogs)
     cat.save(force_insert = True)
 def create_or_update_categories(self, response):
     json_result = loads(response.body.decode('utf8'))
     selector = scrapy.Selector(text=json_result['html'], type="html")
     categories = Category.objects.filter(active=True)
     category_by_name = {c.name.lower(): c for c in categories}
     category_by_css = {}
     for option in selector.xpath(
             "//ul[contains(@class, 'dropdown-menu')]/li/a"):
         category_name = option.extract_first_value_with_xpath('./text()')
         if category_name == '':
             continue
         category_css_name = option.extract_first_value_with_xpath(
             './@value')
         lower_name = category_name.lower()
         if lower_name in category_by_name:
             cat = category_by_name.pop(lower_name)
             if not cat.active:
                 cat.name = category_name.capitalize()
                 cat.active = True
                 cat.save()
                 self.debug_info(
                     'Reactive category {0}'.format(category_name))
         else:
             cat = Category(name=category_name.capitalize(), active=True)
             cat.save()
             self.debug_info(
                 'Create new category {0}'.format(category_name))
         product_list_url = option.extract_first_value_with_xpath('./@href')
         url = urlparse.urljoin(self.__class__.catalogue_base_url,
                                product_list_url)
         yield scrapy.http.Request(url,
                                   callback=self.create_or_update_products)
         category_by_css[category_css_name] = cat
     self.category_by_css = category_by_css
Beispiel #7
0
def import_csv(request):
    if request.method == "POST":
        csv_file = request.FILES.get('csv_file')
        if not csv_file.name.endswith('.csv'):
            error = "Please add 'CSV' File!"
            link = request.META.get('HTTP_REFERER')
            context = {'error': error, 'link': link}
            return render(request, 'back/error.html', context=context)
        file_data = csv_file.read().decode('utf-8')
        lines = file_data.split("\n")  # alt satıra \n ile geçer
        lines.pop(
            0
        )  # burada biz gelen csv'de ilk satırda kolon isimleri olduğundan listeden çıkardık
        lines.pop(len(lines) - 1)  # son eleman '' döndüğünden çıkardık
        for line in lines:
            fields = line.split(
                ',')  # yan yana kolonlar birbirinden ',' ile ayrılır
            try:
                if len(Category.objects.filter(name=fields[0])
                       ) == 0:  # eğer o isimde bir kategori yoksa
                    cat = Category(name=fields[0], count=0)
                    cat.save()
            except:
                print("exception!!!")
    return redirect('panel:category_list')
Beispiel #8
0
    def setUp(self):
        """
            Before each the test function
        """
        self.client = APIClient()

        # Create a fake todo item
        self.user = User(name='test', user_name='te-st',
                         email='*****@*****.**', age=20)
        self.user.save()

        self.category = Category(category_name=1)
        self.category.save()

        self.item_data = {
            'title': 'Test',
            'user': self.user.id,
            'category': self.category.id
        }

        # Fake post request
        self.response = self.client.post(
            '/api/todo/',
            self.item_data,
            format='json'
        )
 def create_or_update_categories(self, response):
     json_result = loads(response.body.decode('utf8'))
     selector = scrapy.Selector(text=json_result['html'], type="html")
     categories = Category.objects.filter(active=True)
     category_by_name = {c.name.lower(): c for c in categories}
     category_by_css = {}
     for option in selector.xpath("//ul[contains(@class, 'dropdown-menu')]/li/a"):
         category_name = option.extract_first_value_with_xpath('./text()')
         if category_name == '':
             continue
         category_css_name = option.extract_first_value_with_xpath('./@value')
         lower_name = category_name.lower()
         if lower_name in category_by_name:
             cat = category_by_name.pop(lower_name)
             if not cat.active:
                 cat.name = category_name.capitalize()
                 cat.active = True
                 cat.save()
                 self.debug_info('Reactive category {0}'.format(category_name))
         else:
             cat = Category(name=category_name.capitalize(), active=True)
             cat.save()
             self.debug_info('Create new category {0}'.format(category_name))
         product_list_url = option.extract_first_value_with_xpath('./@href')
         url = urlparse.urljoin(self.__class__.catalogue_base_url, product_list_url)
         yield scrapy.http.Request(url, callback=self.create_or_update_products)
         category_by_css[category_css_name] = cat
     self.category_by_css = category_by_css
Beispiel #10
0
    def get(_, lang, image_id):

        delete_flag = True

        image_model = Image()
        category_model = Category()

        if lang == 'ja':
            topic_model = Topic()
            introduction_model = Introduction()
        else:
            topic_model = TopicEn()
            introduction_model = IntroductionEn()

        try:
            image = image_model.get_by_image_id(image_id)

            topic_use_flag, topic_use_posts = topic_model.is_use_image(
                image.image_url, image.id)

            if topic_use_flag is True:
                delete_flag = False

            introduction_use_flag, introduction_use_posts = \
                introduction_model.is_use_image(image.image_url)

            if introduction_use_flag is True:
                delete_flag = False

            category_use_flag, category_use_posts = category_model.is_use_image(
                image.image_url)

            if category_use_flag is True:
                delete_flag = False

            use_posts = (
                topic_use_posts +
                category_use_posts +
                introduction_use_posts
            )

            def get_unique_list(seq):
                seen = []
                return [x for x in seq if x not in seen and not seen.append(x)]

            use_posts = get_unique_list(use_posts)

            return JsonResponse({
                'status': 200,
                'delete_flag': delete_flag,
                'use_posts': use_posts,
            }, status=200)

        except Exception as e:
            return JsonResponse({
                'status': 500,
                'message': 'Exception Error ' + str(e)
            }, status=500)
Beispiel #11
0
class TestItemViewSet(TestCase):
    """
        All test functions into the TestItemViewSet are for ItemViewSet
    """

    def setUp(self):
        """
            Before each the test function
        """
        self.client = APIClient()

        # Create a fake todo item
        self.user = User(name='test', user_name='te-st',
                         email='*****@*****.**', age=20)
        self.user.save()

        self.category = Category(category_name=1)
        self.category.save()

        self.item_data = {
            'title': 'Test',
            'user': self.user.id,
            'category': self.category.id
        }

        # Fake post request
        self.response = self.client.post(
            '/api/todo/',
            self.item_data,
            format='json'
        )

    # Post Request
    def test_post_method(self):
        self.assertEqual(self.response.status_code, status.HTTP_201_CREATED)

    # Get Request
    def test_get_method(self):
        todo_count = Item.objects.count()
        response = self.client.get(
            '/api/todo/',
            format='json'
        )
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(todo_count, len(response.data))

    # Retrieve Request
    def test_retrieve_method(self):
        todo_item = Item.objects.get(title='Test')
        response = self.client.get(
            '/api/todo/',
            kwargs={'pk': todo_item.id},
            format='json'
        )

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertContains(response, todo_item)
Beispiel #12
0
def add_category(request):
    if request.method == 'POST':
        name = request.POST['name']
        cat_type = request.POST['cat_type']
        icon = request.FILES['icon']
        category = Category(name = name, cat_type = cat_type, icon = icon)
        if category:
           category.save()
           return redirect('category')
    return render(request, 'category/add-category.html')
Beispiel #13
0
 def delete(self, category_name):
     try:
         email = tornado.escape.xhtml_escape(self.current_user["email"])
         if email in settings.ADMIN_EMAILS:
             m = Category()
             m.delete(category_name)
         self.write('Category deleted!')
     except Exception,e:
         logging.exception(e)
         self.render("404.html")
Beispiel #14
0
def create(request):
    # If this is a post request we insert the person
    if request.POST:
        cat = Category(
            name=request.POST['name'],
        )
        cat.save()

    categories = Category.objects.all()
    context = {'categories': categories}
    messages.add_message(request, messages.INFO, 'Category Create Succesfully')              
    return render(request, 'all_categories.html', context) 
Beispiel #15
0
    def setUp(self):
        self.title = 'Test title'

        self.user = User(
            name='test', user_name='te-st', email='*****@*****.**', age=20)
        self.user.save()

        self.category = Category(category_name=1)
        self.category.save()

        self.item = Item(title=self.title, user=self.user,
                         category=self.category)
    def testNewCategoryWithParent(self):
        """ Verify create with parent and change parent is ok """
        category = Category(name = 'level1', parent = self.blogs)
        self.assertNumQueries(1, category.save())
        self.assertEquals(category.parent.pk, self.blogs.pk)
        print category

        category2 = Category(name = 'level2', parent = category)
        self.assertNumQueries(1, category2.save())

        self.assertEquals(category2.parent.pk, category.pk)
        self.assertEquals(category2.root.pk, self.blogs.pk)

        category3 = Category(name = 'level1.2', parent = self.blogs)
        self.assertNumQueries(1, category3.save())

        category.parent = self.pingpong
        self.assertNumQueries(3, category.save())


        category2 = Category.objects.get(pk = category2.pk)
        category3 = Category.objects.get(pk = category3.pk)
        self.assertEquals(category2.root.pk, self.pingpong.pk)
        self.assertEquals(category2.parent.pk, category.pk)
        self.assertEquals(category3.root.pk, self.blogs.pk)
        self.assertEquals(category3.parent.pk, self.blogs.pk)
Beispiel #17
0
 def post(self, request, format=None):
     users = Users.objects.get(id=request.data['users_id'])
     request.data['users'] = users
     serializer = Category(id=request.data['id'],
                           name=request.data['name'],
                           parent=request.data['parent'],
                           is_featured=request.data['is_featured'],
                           is_active=request.data['is_active'],
                           description=request.data['description'],
                           users=request.data['users'])
     if serializer:
         serializer.save()
         return Response("Added", status=status.HTTP_201_CREATED)
     return Response(serializer, status=status.HTTP_400_BAD_REQUEST)
 def setUp(self):
     self.client = APIClient()
     self.basic_client = Client()
     self.user = User.objects.create_superuser(
         email=EMAIL_TEST, password=PASSWORD_TEST)
     self.other_user = User.objects.create_superuser(
         email=OTHER_EMAIL_TEST, password=PASSWORD_TEST
     )
     self.category3 = Category.objects.create(
         category_title='title3',
         user=self.user,
         category_type='INCOME'
     )
     self.category4 = Category.objects.create(
         category_title='title4',
         user=self.user,
         category_type='EXPENSE'
     )
     self.category5 = Category.objects.create(
         category_title='title5',
         user=self.other_user,
         category_type='EXPENSE'
     )
     self.not_saved_category = Category(
         category_title='not_saved',
         user=self.user,
         category_type='EXPENSE'
     )
Beispiel #19
0
 def get(self):
     try:
         email = tornado.escape.xhtml_escape(self.current_user["email"])
         if email not in settings.ADMIN_EMAILS:
             self.render('denied.html')
         c = Category()
         try:
             result = c.get_all()
         except:
             result = {}
             #when no index structure exists
         #self.write(json.dumps(result))
         self.render("bo_category.html", categories=result)
     except Exception,e:
         logging.exception(e)
         self.render("404.html")
Beispiel #20
0
class VideoForm(forms.Form):
    title = forms.CharField(required=True, error_messages=ERROR_MESSAGES)
    text = forms.CharField(required=True, error_messages=ERROR_MESSAGES)
    youtube_id = forms.CharField(required=True, error_messages=ERROR_MESSAGES)
    published_at = forms.DateTimeField(required=True,
                                       error_messages=ERROR_MESSAGES)
    introductions = forms.MultipleChoiceField(
        required=False,
        widget=forms.CheckboxSelectMultiple,
        choices=lambda: [(v.id, v.id) for v in Introduction.get_all()],
        error_messages=ERROR_MESSAGES)
    topics = forms.MultipleChoiceField(
        required=False,
        widget=forms.CheckboxSelectMultiple,
        choices=lambda: [(v.id, v.id) for v in Topic.get_all()],
        error_messages=ERROR_MESSAGES)
    categories = forms.MultipleChoiceField(
        required=False,
        widget=forms.CheckboxSelectMultiple,
        choices=lambda: [(v.id, v.id) for v in Category.get_all()],
        error_messages=ERROR_MESSAGES)
    videos = forms.MultipleChoiceField(
        required=False,
        widget=forms.CheckboxSelectMultiple,
        choices=lambda: [(v.id, v.id) for v in Video.get_all()],
        error_messages=ERROR_MESSAGES)
Beispiel #21
0
    def get_context_data(self, **kwargs):
        context = super(MixtureDetailView, self).get_context_data(**kwargs)

        try:
            if 'slug' in self.kwargs:  # this is backward compatibility
                mixture = Mixture.published.get(
                    Q(slug_en=self.kwargs['slug'])
                    | Q(slug_es=self.kwargs['slug']))
            else:
                # normal mixture detail request
                mixture = Mixture.published.get(pk=self.kwargs['pk'])

        except Mixture.DoesNotExist:
            raise Http404()

        context['object'] = mixture

        currency_code = self.request.GET.get(
            'c', settings.CURRENCY_DEFAULT).upper()

        currency = Currency.objects.get(code=currency_code)
        context['currency'] = currency

        context['category_tree'] = Category.tree(mixture.category)
        context['form'] = ContactForm(request=self.request)
        return context
Beispiel #22
0
    def get_context_data(self, **kwargs):
        context = super(MixtureDetailView, self).get_context_data(**kwargs)

        try:
            if 'slug' in self.kwargs:  # this is backward compatibility
                mixture = Mixture.published.get(
                    Q(slug_en=self.kwargs['slug']) |
                    Q(slug_es=self.kwargs['slug'])
                )
            else:
                # normal mixture detail request
                mixture = Mixture.published.get(pk=self.kwargs['pk'])

        except Mixture.DoesNotExist:
            raise Http404()

        context['object'] = mixture

        currency_code = self.request.GET.get(
            'c', settings.CURRENCY_DEFAULT
        ).upper()

        currency = Currency.objects.get(code=currency_code)
        context['currency'] = currency

        context['category_tree'] = Category.tree(mixture.category)
        context['form'] = ContactForm(request=self.request)
        return context
Beispiel #23
0
def home_view(request):
    categories, income = Operation.get_user_income_by_category(request.user)
    categories2, outcome2 = Operation.get_user_outcome_by_category(
        request.user)

    fig_income = px.pie(categories,
                        categories,
                        income,
                        title={
                            'text': "Income",
                            'y': 0.9,
                            'x': 0.45,
                            'xanchor': 'center',
                            'yanchor': 'top',
                            'font': {'family': 'Arial',
                                     'size': 20
                                     }
                        },

                        width=500,
                        height=450)

    fig_outcome = px.pie(categories2,
                         categories2,
                         outcome2,
                         title={
                             'text': "Outcome",
                             'y': 0.9,
                             'x': 0.45,
                             'xanchor': 'center',
                             'yanchor': 'top',
                             'font': {'family': 'Arial',
                                      'size': 20
                                      }
                         },
                         width=500,
                         height=450)

    # plot(fig, filename='statistic/templates/piechart_income')
    pie_income = plot(fig_income, output_type='div')
    pie_outcome = plot(fig_outcome, output_type='div')

    income = Operation.get_user_income(request.user)
    outcome = Operation.get_user_outcome(request.user)
    current = Operation.get_user_current(request.user)
    operation_list = Operation.get_user_operation(request.user)
    user_category = Category.get_user_category(request.user)

    request.session['current'] = current

    return render(request,
                  'statistic.html',
                  {'income': income,
                   'outcome': outcome,
                   'current': current,
                   'operation_list': operation_list,
                   'user_category': user_category,
                   'pie_income': pie_income,
                   'pie_outcome': pie_outcome})
Beispiel #24
0
 def changelist_view(self, request, *args, **kwargs):
     cats = Category.get_categories_as_keys()
     cats = dict([(y, "=>".join(x)) for x, y in cats.items()])
     self._categories_as_keys = cats
     request._getting_changelist = True
     result = super(ProductAdmin, self).changelist_view(request, *args, **kwargs)
     request._getting_changelist = False
     return result
Beispiel #25
0
 def GET(self, category_id=None):
     if category_id:
         category = Category.get_by_id(int(category_id))
         category.delete()
         
         clear_cache()
     
     return web.seeother('/admin/categories')
Beispiel #26
0
 def changelist_view(self, request, *args, **kwargs):
     cats = Category.get_categories_as_keys()
     cats = dict([(y, '=>'.join(x)) for x, y in cats.items()])
     self._categories_as_keys = cats
     request._getting_changelist = True
     result = super(ProductAdmin, self).changelist_view(request, *args, **kwargs)
     request._getting_changelist = False
     return result
Beispiel #27
0
 def GET(self, category_id=None):
     category = None
     if category_id:
         category = Category.get_by_id(int(category_id))
         title = u'修改分类'
     else:
         title = u'新增分类'
     
     return render('admin/category.html',category=category,title=title)
Beispiel #28
0
    def remove_category(cls, video_id):
        all_category_ids = [v.id for v in Category.get_all()]
        try:
            video = cls.objects.get(id=video_id)
            for v in all_category_ids:
                video.category.remove(v)

        except:
            pass
Beispiel #29
0
class TestModel(TestCase):
    def setUp(self):
        self.title = 'Test title'

        self.user = User(
            name='test', user_name='te-st', email='*****@*****.**', age=20)
        self.user.save()

        self.category = Category(category_name=1)
        self.category.save()

        self.item = Item(title=self.title, user=self.user,
                         category=self.category)

    def test_item_model(self):
        old_item = Item.objects.count()
        self.item.save()
        new_item = Item.objects.count()
        self.assertNotEqual(old_item, new_item)
Beispiel #30
0
    def post(request, lang, category_id):

        category_model = Category()
        category = category_model.get_by_id(category_id)
        groups = Group.get_all()
        form = CategoryForm(request.POST)

        if category is None:
            return HttpResponseRedirect('/{}/admin/categories'.format(lang))

        if form.errors:
            messages.add_message(request, messages.INFO,
                                 dict(form.errors.items()))

        if form.is_valid():
            try:
                category_model.edit_category(
                    category_id, {
                        'name_ja': form.cleaned_data.get('name_ja'),
                        'name_en': form.cleaned_data.get('name_en'),
                        'image': form.cleaned_data.get('image'),
                        'order': form.cleaned_data.get('order'),
                        'group': Group.get_by_id(
                            form.cleaned_data.get('group')),
                    })

                return HttpResponseRedirect(
                    '/{}/admin/categories'.format(lang))

            except:
                pass

        title = category.name_ja

        return TemplateResponse(
            request, 'category.html', {
                'title': title + ' | カテゴリー | FEED App 管理',
                'category': category,
                'groups': groups,
                'form_data': form.cleaned_data,
                'error_messages': get_error_message(request),
                'lang': lang,
            })
Beispiel #31
0
    def get_category_outcome_per_month(user_id, category_id):
        '''

        :param user_id:
        :param category_id:
        :return: dict with outcome per month
        {month:outcome}
        '''

        outcome_per_month = {key: 0 for key in range(1, 13)}
        category = Category.get_category(category_id)

        current_date = datetime.datetime.today()
        current_year = current_date.year
        current_month = current_date.month

        if category.type == 'Current':
            for i in range(current_month + 1, 13):
                a = list(
                    Operation.objects.filter(from_category__user_id=user_id,
                                             from_category=category.id,
                                             date__month=i,
                                             date__year=current_year - 1))

                outcome_per_month[i] = sum(j.value for j in a)

            for i in range(1, current_month + 1):
                a = list(
                    Operation.objects.filter(from_category__user_id=user_id,
                                             from_category=category.id,
                                             date__month=i,
                                             date__year=current_year))

                outcome_per_month[i] = sum(j.value for j in a)

        else:
            for i in range(current_month + 1, 13):
                a = list(
                    Operation.objects.filter(to_category__user_id=user_id,
                                             to_category=category.id,
                                             date__month=i,
                                             date__year=current_year - 1))

                outcome_per_month[i] = sum(j.value for j in a)

            for i in range(1, current_month + 1):
                a = list(
                    Operation.objects.filter(to_category__user_id=user_id,
                                             to_category=category.id,
                                             date__month=i,
                                             date__year=current_year))

                outcome_per_month[i] = sum(j.value for j in a)

        return outcome_per_month
Beispiel #32
0
    def test_create_product(self):
        category = Category(name='Category 1')
        category.save()
        product = Product.objects.create(name='product 1',
                                         slug='product-1',
                                         description='description',
                                         images='',
                                         price=600,
                                         stock=True,
                                         is_available=True,
                                         category=category)

        self.assertEqual(product.name, 'product 1')
        self.assertEqual(product.slug, 'product-1')
        self.assertEqual(product.description, 'description')
        self.assertEqual(product.images, '')
        self.assertEqual(product.price, 600)
        self.assertEqual(product.stock, True)
        self.assertEqual(product.is_available, True)
        self.assertEqual(product.category, category)
Beispiel #33
0
 def POST(self):
     data = web.data()
     
     sorted_data = json.loads(data)
     for category_id, sort in sorted_data.iteritems():
         category = Category.get_by_id(int(category_id))
         category.sort = sort
         category.save()
     
     clear_cache()
     return json.dumps({'status': 'ok'})
Beispiel #34
0
    def get_outcome_of_all_categories_per_month(user_id):
        categories = Category.get_user_category(user_id)
        outcome_per_month = {key: 0 for key in range(1, 13)}
        for category in categories:
            if category.type != 'Current':
                category_income = Operation.get_category_outcome_per_month(
                    user_id, category.id)

                for month, outcome in category_income.items():
                    outcome_per_month[month] += outcome

        return outcome_per_month
Beispiel #35
0
    def post(self, request):
        try:
            body: str = request.body.decode('utf-8')
            req_body: Dict = loads(body)
            try:
                Category.objects.get(name=req_body['name'])
                err_resp = {
                    'success': False,
                    'message':
                    f'Category with {req_body["name"]} already exists.'
                }
                return JsonResponse(data=err_resp, status=409)
            except Category.DoesNotExist:
                category = Category()
                category.name = req_body['name']
                category.type = req_body['type'] if req_body['type'] in [
                    'DEVICE',
                    'GARMENTS',
                    'ACCESSORIES',
                ] else 'DEVICE'
                category.save()

                data = category_serializer(category)
                return JsonResponse(data=data, status=201)
        except Exception as e:
            err_resp = {'success': False, 'message': str(e)}
            return JsonResponse(data=err_resp, status=500)
Beispiel #36
0
    def post(request, lang):

        form = CategoryForm(request.POST)
        category_model = Category()

        if form.errors:
            messages.add_message(request, messages.INFO,
                                 dict(form.errors.items()))

        if form.is_valid():
            try:
                category_model.create_category({
                    'name_ja':
                    form.cleaned_data.get('name_ja'),
                    'name_en':
                    form.cleaned_data.get('name_en'),
                    'image_url':
                    form.cleaned_data.get('image_url'),
                    'order':
                    form.cleaned_data.get('order'),
                    'group':
                    Group.get_by_id(form.cleaned_data.get('group')),
                })

                return HttpResponseRedirect(
                    '/{}/admin/categories'.format(lang))

            except:
                pass

        groups = Group.get_all()

        return TemplateResponse(
            request, 'category_create.html', {
                'title': '新規投稿 | カテゴリー | FEED App 管理',
                'groups': groups,
                'form_data': form.cleaned_data,
                'error_messages': get_error_message(request),
                'lang': lang,
            })
def create_categories():

	Category.objects.all().delete()

	for pk, fields in categorias.iteritems():
		c = Category(pk=pk)
		c.name = fields['name']
		c.slug = fields['slug']
		c.description = fields['description']
		c.published = fields['active']
		c.save()
Beispiel #38
0
    def get(request, lang, category_id):

        category_model = Category()

        category = category_model.get_by_id(category_id)

        groups = Group.get_all()

        if category is None:
            raise Http404

        title = category.name_ja

        return TemplateResponse(
            request, 'category.html', {
                'title': title + ' | カテゴリー | FEED App 管理',
                'category': category,
                'groups': groups,
                'error_messages': {},
                'form_data': {},
                'lang': lang,
            })
Beispiel #39
0
 def GET(self, category_name):
     if category_name.isdigit():
         category = Category.get_by_id(int(category_name))
     else:
         category = Category.all().filter('alias =', category_name).get()
     
     inp = web.input()
     # bookmark = inp.get('bookmark')
     # 
     # query = PagerQuery(Post).filter('hidden =', False)
     # query.filter('category =', category)
     # query.order('-date')
     # prev, posts, next = query.fetch(blog.post_pagesize, bookmark)
     page = inp.get('page')
     if not page:
         page = 1
     pager = Pager(Post, blog.post_pagesize).order('-date')
     pager.filter('hidden =', False)
     pager.filter('category =', category)
     posts = pager.fetch(page)
     
     return render('theme/index.html',posts=posts,pager=pager)#prev=prev,next=next)
Beispiel #40
0
def create_view(request):
    user_category = Category.get_user_category(user_id=request.user)

    if request.method == 'POST':
        to_category = request.POST.get('to')
        from_category = request.POST.get('from')
        value = request.POST.get('value')
        date = request.POST.get('date')

        from_category_obj = Category.get_category_by_name(user_id=request.user,
                                                          name=from_category)
        to_category_obj = Category.get_category_by_name(user_id=request.user,
                                                        name=to_category)

        if from_category_obj.type == to_category_obj.type or (
                from_category_obj.type != "Current"
                and to_category_obj.type != 'Current'):
            return HttpResponse('ONE CATEGORY MUST BE CURRENT')
        Operation.create(from_category_obj, to_category_obj, value, date)
        return redirect('operation_home')

    return render(request, 'operation_create.html',
                  {'user_category': user_category})
 def create_or_update_categories(self, selector):
     categories = Category.objects.filter(active=True)
     category_by_name = {c.name.lower(): c for c in categories}
     category_by_css = {}
     for option in selector.xpath('//select[@name="category"]/option'):
         category_name = option.extract_first_value_with_xpath('./text()')
         if category_name == '':
             continue
         category_css_name = option.extract_first_value_with_xpath('./@value')
         lower_name = category_name.lower()
         if lower_name in category_by_name:
             cat = category_by_name.pop(lower_name)
             if not cat.active:
                 cat.name = category_name.capitalize()
                 cat.active = True
                 cat.save()
                 self.debug_info('Reactive category {0}'.format(category_name))
         else:
             cat = Category(name=category_name.capitalize(), active=True)
             cat.save()
             self.debug_info('Create new category {0}'.format(category_name))
         category_by_css[category_css_name] = cat
     self.category_by_css = category_by_css
Beispiel #42
0
def save_or_update(req):
    msg = ''
    if req.method == 'POST':
        if int(req.POST["id"]) > 0:
            category = Category(id=req.POST["id"], type=req.POST["type"])
            msg = "Updation Operation Successfully...!"
            category.save()
        else:
            category = Category(type=req.POST["type"])
            msg = "Add Operation Successfully...!"
            category.save()

    return render(req, 'category.html', {
        "cat": dummy_category(),
        "note": msg,
        "categories": get_active_category()
    })
Beispiel #43
0
    def get_user_operation_by_category(user_id, category_id):
        '''

        :param user_id:
        :param category_id:
        :return: All operations with category
        '''
        operation_list = Operation.get_user_operation(user_id)
        category = Category.get_category(category_id)
        data = []

        for operation in operation_list:
            if operation.from_category.name == category.name \
            or operation.to_category.name == category.name:
                data.append(operation)
        return data
Beispiel #44
0
    def add_category(cls, video_id, category_ids):
        category_ids = list(map(int, category_ids))
        all_category_ids = [v.id for v in Category.get_all()]
        try:
            video = cls.objects.get(id=video_id)
            for v in all_category_ids:
                if v in category_ids:
                    try:
                        video.category.add(v)
                    except:
                        pass
                else:
                    video.category.remove(v)

        except:
            pass
Beispiel #45
0
 def body(self):
     content = memcache.get('widget_category_list')
     if not content:
         category_list = Category.all().order('sort')
     
         content = []
         write = content.append
         write('<ul>')
         for category in category_list:
             write('<li><a href="%s">%s</a>(%s)</li>' % 
                     (category.getUrl(), category.name, category.count))
         write('</ul>')
         content = '\n'.join(content)
         memcache.set('widget_category_list', content)
     
     return content
Beispiel #46
0
 def GET(self, post_id=None):
     post = {}
     if post_id:
         # post = Post.get(db.Key.from_path(Post.kind(), int(post_id)))
         post = Post.get_by_id(int(post_id))
         title = u'修改日志'
     else:
         title = u'写新日志'
         post['date'] = datetime.now()
     
     categories = Category.all().order('sort')
     
     return render('admin/post.html',
                   post=post,
                   title=title,
                   categories=categories)
Beispiel #47
0
def requestView(request):
    form = RequestForm(request.POST or None)
    if form.is_valid():
        new_request = Request(
            user = request.user,
            dateS = request.POST['dateS'],
            dateE = request.POST['dateE'],
            category = Category(request.POST['category']),
            )
        new_request.save()

    context = {
        'form': form
        }

    return render(request, "request.html", context)
Beispiel #48
0
 def POST(self, category_id=None):
     if category_id:
         category = Category.get_by_id(int(category_id))
     else:
         category = Category()
         max_sort_category = Category.all().order('-sort').get()
         if max_sort_category:
             # max_sort_category = max_sort_category.pop()
             max_sort = max_sort_category.sort
             if not max_sort:
                 max_sort = 0
         else:
             max_sort = 0
         category.sort = max_sort + 1
     
     inp = web.input()
     category.name = inp.name
     category.alias = inp.get('alias')
     category.save()
     
     clear_cache()
     return web.seeother('/admin/categories')
Beispiel #49
0
 def get(self, request, *args, **kwargs):
     # NOTE: with tree structure
     category_pairs = Category.get_categories_tree()
     return Response([CategoryPairSerializer(cate, sub_cates).data for cate, sub_cates in category_pairs])
 def testNewCategory(self):
     """ Verify category creating is ok """
     category = Category(name = 'test')
     category.save()
     self.assertNotEquals(category.root, None)
     self.assertEquals(category.root.pk, category.pk)
Beispiel #51
0
 def POST(self, post_id=None):
     """保存日志信息"""
     import pytz
     
     if post_id:
         post = Post.get_by_id(int(post_id))
     else:
         post = Post()
     
     inp = web.input()
     
     post.title = inp.title
     post.alias = inp.alias
     post.content = inp.content
     post.excerpt = inp.excerpt
     if inp.get('date'):
         tz = pytz.timezone(blog.timezone)
         date = inp.get('date')
         date = datetime.strptime(date, '%Y-%m-%d %H:%M:%S')
         date_tz = date.replace(tzinfo=tz)
         # datetime = time.mktime(date)
         post.date = date_tz
     post.allow_comment = bool(inp.get('allow_comment'))
     post.allow_ping = bool(inp.get('allow_ping'))
     post.hidden = bool(inp.get('hidden'))
     
     # 以下分类代码写的比较乱
     # 文章添加分类最简单,直接分类统计加1
     # 分类修改则取得原分类减1,新分类加1
     # 删除分类则将旧分类减1
     category_key = inp.get('category')
     if category_key:
         category = Category.get(category_key)
     if post.category:
         if unicode(post.category.key()) != unicode(category_key):
             post.category.count = post.category.count - 1
             post.category.save()
             if category_key:
                 post.category = category
                 category.count = category.count + 1
                 category.save()
             else:
                 post.category = None
     elif category_key:
         post.category = category
         category.count = category.count + 1
         category.save()
     
     tags = inp.tags
     if tags:
         tags = tags.split(',')
         post.tags = tags
         for tag in tags:
             Tag.add(tag)
     post.save()
     
     clear_cache()
     
     from google.appengine.api import taskqueue
     queue = taskqueue.Queue()
     url = '/task/ping_sites'
     ping_task = taskqueue.Task(countdown=5, url=url)
     queue.add(ping_task)
     
     raise web.seeother('/admin/posts')
Beispiel #52
0
 def get(self, request, category_name, *args, **kwargs):
     category = Category.get_by_name(category_name)
     return Response(CategorySerializer(category).data)
Beispiel #53
0
 def GET(self):
     categories = Category.all().order('sort')
     
     return render('admin/categories.html',categories=categories)
Beispiel #54
0
 def get(self, request, *args, **kwargs):
     # NOTE: all end node category
     categories = Category.get_recommend_cates()
     return Response([CategorySerializer(cate).data for cate in categories])