Example #1
0
def add_category():
 
    category_id = request.json.get("id")
    category_name = request.json.get("name")

    if not category_name:
        return jsonify(errno=Code.PARAMERR,errmsg="分类名称不能为空")

    if category_id: 
        try:
            category = Category.query.get(category_id)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=Code.DBERR,errmsg="获取分类失败")

        if not category:
            return jsonify(errno=Code.NODATA,errmsg="该分类不存在")

        category.name = category_name

    else: #新增
        category = Category(name=category_name)

        #添加分类到数据库中
        try:
            db.session.add(category)
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR,errmsg="分类新增失败")
    return jsonify(errno=Code.OK,errmsg="操作成功")
Example #2
0
def add_category():
    list_category = ['Экономика', 'Туризм', 'Спорт', 'СНГ', 'Силовые структуры', 'Россия', 'Происшествия',
                 'Политика', 'Нацпроекты', 'Наука и техника', 'Мир', 'Культура', 'Интернет и СМИ',
                 'Власть', 'Авто', 'Digital', '']
    category_in_to_base = []

    for c in Category.objects.all():
        category_in_to_base.append(c.name)

    for category_name in list_category:
        if category_name not in category_in_to_base:
            category = Category()
            category.name = category_name
            category.save()
        else:
            print('Категория существует в базе.')
Example #3
0
def test_catagory_model(name, description, type, expected_name, expected_desc,
                        expected_type):
    data = Category(name=name, description=description, content_type=type)

    assert data.name == expected_name
    assert data.description == expected_desc
    assert data.content_type == expected_type
Example #4
0
    def test_edit_news(self):
        category = Category()
        category.name = 'Экономика'
        category.description = 'Новости экономики'
        category.slug = 'economy'
        category.save()

        news = News()
        news.title = 'Моя первая новость'
        news.announcement = 'Анонс первой новости ++'
        news.text = 'Текст первой новости!!!'
        news.pub_date = timezone.now()
        news.category = category
        news.save()

        self.client.login(username='******', password='******')

        response = self.client.post('/admin/news/news/' + str(news.id) + '/', {
            'title': 'Моя вторая новость',
            'announcement': 'Анонс второй новости',
            'text': 'Текст второй новости',
            'pub_date_0': '2014-10-15',
            'pub_date_1': '16:07:00',
            'category': str(category.id)
        },
                                    follow=True)

        self.assertContains(response, 'успешно изменен', status_code=200)

        all_news = News.objects.all()
        self.assertEquals(len(all_news), 1)
        only_news = all_news[0]
        self.assertEquals(only_news.title, 'Моя вторая новость')
        self.assertEquals(only_news.announcement, 'Анонс второй новости')
        self.assertEquals(only_news.text, 'Текст второй новости')
Example #5
0
    def test_delete_new(self):
        category = Category()
        category.name = 'Экономика'
        category.description = 'Новости экономики'
        category.slug = 'economy'
        category.save()

        news = News()
        news.title = 'Моя первая новость'
        news.announcement = 'Анонс первой новости ++'
        news.text = 'Текст первой новости!!!'
        news.pub_date = timezone.now()
        news.category = category
        news.save()

        all_news = News.objects.all()
        self.assertEquals(len(all_news), 1)

        self.client.login(username='******', password='******')

        response = self.client.post('/admin/news/news/' + str(news.id) +
                                    '/delete/', {'post': 'yes'},
                                    follow=True)
        self.assertContains(response, 'успешно удален', status_code=200)

        all_news = News.objects.all()
        self.assertEquals(len(all_news), 0)
Example #6
0
    def test_category_page(self):
        category = Category()
        category.name = 'Экономика'
        category.description = 'Новости экономики'
        category.slug = 'economy'
        category.save()

        news = News()
        news.title = 'Моя первая новость'
        news.announcement = 'Анонс первой новости'
        news.pub_date = timezone.now()
        news.category = category
        news.save()

        all_news = News.objects.all()
        self.assertEquals(len(all_news), 1)
        only_news = all_news[0]
        self.assertEquals(only_news, news)

        category_url = news.category.get_absolute_url()
        response = self.client.get(category_url)
        self.assertContains(response, news.category.name, status_code=200)

        #проверяем атрибуты
        self.assertEquals(only_news.title, 'Моя первая новость')
        self.assertEquals(only_news.announcement, 'Анонс первой новости')
        self.assertEquals(only_news.pub_date.day, news.pub_date.day)
        self.assertEquals(only_news.pub_date.year, news.pub_date.year)
Example #7
0
    def test_create_news(self):
        category = Category()
        category.name = 'Экономика'
        category.description = 'Новости экономики'
        category.slug = 'economy'
        category.save()

        self.client.login(username='******', password='******')

        response = self.client.get('/admin/news/news/add/')
        self.assertEquals(response.status_code, 200)

        response = self.client.post('/admin/news/news/add/', {
            'title': 'Моя первая новость',
            'announcement': 'Анонс первой новости',
            'text': 'Плюс текст первой новости',
            'pub_date_0': '2014-10-15',
            'pub_date_1': '15:35:00',
            'category': str(category.id)
        },
                                    follow=True)
        self.assertContains(response, 'успешно добавлен', status_code=200)

        all_news = News.objects.all()
        self.assertEquals(len(all_news), 1)
Example #8
0
    def test_create_news(self):
        category = Category()
        category.name = 'Экономика'
        category.description = 'Новости экономики'
        category.slug = 'economy'
        category.save()

        self.client.login(username='******', password='******')

        response = self.client.get('/admin/news/news/add/')
        self.assertEquals(response.status_code, 200)

        response = self.client.post('/admin/news/news/add/', {
            'title': 'Моя первая новость',
            'announcement': 'Анонс первой новости',
            'text': 'Плюс текст первой новости',
            'pub_date_0': '2014-10-15',
            'pub_date_1': '15:35:00',
            'category': str(category.id)
            },
            follow=True
            )
        self.assertContains(response, 'успешно добавлен', status_code=200)

        all_news = News.objects.all()
        self.assertEquals(len(all_news), 1)
Example #9
0
    def test_delete_new(self):
        category = Category()
        category.name = 'Экономика'
        category.description = 'Новости экономики'
        category.slug = 'economy'
        category.save()

        news = News()
        news.title = 'Моя первая новость'
        news.announcement = 'Анонс первой новости ++'
        news.text = 'Текст первой новости!!!'
        news.pub_date = timezone.now()
        news.category = category
        news.save()

        all_news = News.objects.all()
        self.assertEquals(len(all_news), 1)

        self.client.login(username='******', password='******')

        response = self.client.post('/admin/news/news/' + str(news.id) + '/delete/', {
            'post':'yes'
            },
            follow=True
            )
        self.assertContains(response, 'успешно удален', status_code=200)

        all_news = News.objects.all()
        self.assertEquals(len(all_news), 0)
Example #10
0
    def test_category_page(self):
        category = Category()
        category.name = 'Экономика'
        category.description = 'Новости экономики'
        category.slug = 'economy'
        category.save()

        news = News()
        news.title = 'Моя первая новость'
        news.announcement = 'Анонс первой новости'
        news.pub_date = timezone.now()
        news.category = category
        news.save()

        all_news = News.objects.all()
        self.assertEquals(len(all_news), 1)
        only_news = all_news[0]
        self.assertEquals(only_news, news)

        category_url = news.category.get_absolute_url()
        response = self.client.get(category_url)
        self.assertContains(response, news.category.name, status_code=200)

        #проверяем атрибуты
        self.assertEquals(only_news.title, 'Моя первая новость')
        self.assertEquals(only_news.announcement, 'Анонс первой новости')
        self.assertEquals(only_news.pub_date.day, news.pub_date.day)
        self.assertEquals(only_news.pub_date.year, news.pub_date.year)
Example #11
0
        def parser3():
            url = 'https://www.gazeta.ru/export/rss/first.xml'
            r = requests.get(url)
            soup = BeautifulSoup(r.text, 'html.parser')
            item_xml = soup.find_all('item')[0]
            get_title = item_xml.find('title').text
            get_category = item_xml.find('category').text
            get_link = item_xml.find('guid').text
            icon = 'https://www.gazeta.ru/i/gazeta_og_image.jpg'

            list_category = []
            list_title = []

            for c in Category.objects.all():
                list_category.append(c.name)

            if get_category in list_category:
                print(get_category, " Категория существует")
            elif get_category not in list_category:
                new_category = Category()
                new_category.name = get_category
                new_category.save()
                print("Добавлена новая категория ", get_category)

            for t in News.objects.all():
                list_title.append(t.title)

            if get_title in list_title:
                print("новость существует в базе")
            elif get_title not in list_title:
                print("Добавление новой новости")
                new_news = News()
                new_news.title = get_title
                new_news.category_id = Category.objects.get(name=get_category).pk
                new_news.url_source = get_link
                new_news.icon = icon
                new_news.save()
Example #12
0
def index(request):
    news = News.objects.order_by('-published_date')
    context = dict()
    context['latest_news'] = news[:10]
    context['top_news'] = news[:3]

    news_by_category = []

    for category in Category.menus():
        news_by_category.append(
            (category, News.objects.filter(
                category=category).order_by('-published_date')[:3]))

    context['news_by_category'] = news_by_category

    return render(request, 'index.html', context)
Example #13
0
    def test_create_category(self):
        category = Category()
        category.name = 'Экономика'
        category.description = 'Новости экономики'
        category.slug = 'economy'
        category.save()

        all_categories = Category.objects.all()
        self.assertEquals(len(all_categories), 1)
        only_category = all_categories[0]
        self.assertEquals(only_category, category)

        self.assertEquals(only_category.name, 'Экономика')
        self.assertEquals(only_category.description, 'Новости экономики')
Example #14
0
    def test_delete_category(self):
        category = Category()
        category.name = 'Экономика'
        category.description = 'Новости экономики'
        category.slug = 'economy'
        category.save()

        self.client.login(username='******', password='******')

        response = self.client.post('/admin/news/category/' +
                                    str(category.id) + '/delete/',
                                    {'post': 'yes'},
                                    follow=True)
        self.assertContains(response, 'успешно удален', status_code=200)
        all_categories = Category.objects.all()
        self.assertEquals(len(all_categories), 0)
Example #15
0
    def test_create_category(self):
        category = Category()
        category.name = 'Экономика'
        category.description = 'Новости экономики'
        category.slug = 'economy'
        category.save()

        all_categories = Category.objects.all()
        self.assertEquals(len(all_categories), 1)
        only_category = all_categories[0]
        self.assertEquals(only_category, category)

        self.assertEquals(only_category.name, 'Экономика')
        self.assertEquals(only_category.description, 'Новости экономики')
Example #16
0
    def test_delete_category(self):
        category = Category()
        category.name = 'Экономика'
        category.description = 'Новости экономики'
        category.slug = 'economy'
        category.save()

        self.client.login(username='******', password='******')

        response = self.client.post('/admin/news/category/' + str(category.id) + '/delete/', {
            'post': 'yes'
            },
            follow=True
            )
        self.assertContains(response, 'успешно удален', status_code=200)
        all_categories = Category.objects.all()
        self.assertEquals(len(all_categories), 0)
Example #17
0
    def test_create_news(self):
        category = Category()
        category.name = 'Экономика'
        category.description = 'Новости экономики'
        category.slug = 'economy'
        category.save()

        #создаем новость и заполняем поля
        news = News()

        #устанавливаем атрибуты
        news.title = 'Моя первая новость'
        news.announcement = 'Анонс первой новости ++'
        news.text = 'Текст первой новости!!!'
        news.pub_date = timezone.now()
        news.category = category

        #сохраняем в бд
        news.save()

        #проверяем что новость доавбилась в базу
        all_news = News.objects.all()
        self.assertEquals(len(all_news), 1)
        only_news = all_news[0]
        self.assertEquals(only_news, news)

        #проверяем атрибуты
        self.assertEquals(only_news.title, 'Моя первая новость')
        self.assertEquals(only_news.announcement, 'Анонс первой новости ++')
        self.assertEquals(only_news.text, 'Текст первой новости!!!')
        self.assertEquals(only_news.pub_date.day, news.pub_date.day)
        self.assertEquals(only_news.pub_date.month, news.pub_date.month)
        self.assertEquals(only_news.pub_date.year, news.pub_date.year)
        self.assertEquals(only_news.pub_date.hour, news.pub_date.hour)
        self.assertEquals(only_news.pub_date.minute, news.pub_date.minute)
        self.assertEquals(only_news.pub_date.second, news.pub_date.second)
        self.assertEquals(only_news.category.name, 'Экономика')
        self.assertEquals(only_news.category.description, 'Новости экономики')
Example #18
0
    def test_edit_category(self):
        category = Category()
        category.name = 'Экономика'
        category.description = 'Новости экономики'
        category.slug = 'economy'
        category.save()

        self.client.login(username='******', password='******')

        response = self.client.post('/admin/news/category/' +
                                    str(category.id) + '/', {
                                        'name': 'Политика',
                                        'description': 'Новости политики',
                                        'slug': 'politics'
                                    },
                                    follow=True)
        self.assertContains(response, 'успешно изменен', status_code=200)

        all_categories = Category.objects.all()
        self.assertEquals(len(all_categories), 1)
        only_category = all_categories[0]
        self.assertEquals(only_category.name, 'Политика')
        self.assertEquals(only_category.description, 'Новости политики')
Example #19
0
    def test_news_page(self):
        category = Category()
        category.name = 'Экономика'
        category.description = 'Новости экономики'
        category.slug = 'economy'
        category.save()

        news = News()
        news.title = 'Моя первая новость'
        news.text = 'Текст первой новости'
        news.pub_date = timezone.now()
        news.category = category
        news.save()

        all_news = News.objects.all()
        self.assertEquals(len(all_news), 1)

        response = self.client.get('/news/' + str(news.id) + '/')
        self.assertContains(response, news.title, status_code=200)
        self.assertContains(response, news.text)
        self.assertContains(response, news.pub_date.year)
        # выдает на англ и сравнивает с русским - не отрабатывает self.assertContains(response, news.pub_date.strftime('%b'))
        self.assertContains(response, news.pub_date.day)
        self.assertContains(response, news.category.name)
Example #20
0
    def test_create_news(self):
        category = Category()
        category.name = 'Экономика'
        category.description = 'Новости экономики'
        category.slug = 'economy'
        category.save()

        #создаем новость и заполняем поля
        news = News()

        #устанавливаем атрибуты
        news.title = 'Моя первая новость'
        news.announcement = 'Анонс первой новости ++'
        news.text = 'Текст первой новости!!!'
        news.pub_date = timezone.now()
        news.category = category

        #сохраняем в бд
        news.save()

        #проверяем что новость доавбилась в базу
        all_news = News.objects.all()
        self.assertEquals(len(all_news), 1)
        only_news = all_news[0]
        self.assertEquals(only_news, news)

        #проверяем атрибуты
        self.assertEquals(only_news.title, 'Моя первая новость')
        self.assertEquals(only_news.announcement, 'Анонс первой новости ++')
        self.assertEquals(only_news.text, 'Текст первой новости!!!')
        self.assertEquals(only_news.pub_date.day, news.pub_date.day)
        self.assertEquals(only_news.pub_date.month, news.pub_date.month)
        self.assertEquals(only_news.pub_date.year, news.pub_date.year)
        self.assertEquals(only_news.pub_date.hour, news.pub_date.hour)
        self.assertEquals(only_news.pub_date.minute, news.pub_date.minute)
        self.assertEquals(only_news.pub_date.second, news.pub_date.second)
        self.assertEquals(only_news.category.name, 'Экономика')
        self.assertEquals(only_news.category.description, 'Новости экономики')
Example #21
0
    def test_edit_category(self):
        category = Category()
        category.name = 'Экономика'
        category.description = 'Новости экономики'
        category.slug = 'economy'
        category.save()

        self.client.login(username='******', password='******')

        response = self.client.post('/admin/news/category/' + str(category.id) + '/', {
            'name': 'Политика',
            'description': 'Новости политики',
            'slug': 'politics'
            },
            follow=True
            )
        self.assertContains(response, 'успешно изменен', status_code=200)

        all_categories = Category.objects.all()
        self.assertEquals(len(all_categories), 1)
        only_category = all_categories[0]
        self.assertEquals(only_category.name, 'Политика')
        self.assertEquals(only_category.description, 'Новости политики')
Example #22
0
    def test_edit_news(self):
        category = Category()
        category.name = 'Экономика'
        category.description = 'Новости экономики'
        category.slug = 'economy'
        category.save()

        news = News()
        news.title = 'Моя первая новость'
        news.announcement = 'Анонс первой новости ++'
        news.text = 'Текст первой новости!!!'
        news.pub_date = timezone.now()
        news.category = category
        news.save()

        self.client.login(username='******', password='******')
        
        response = self.client.post('/admin/news/news/' + str(news.id) + '/', {
            'title': 'Моя вторая новость',
            'announcement': 'Анонс второй новости',
            'text': 'Текст второй новости',
            'pub_date_0': '2014-10-15',
            'pub_date_1': '16:07:00',
            'category': str(category.id)
            },
            follow=True
            )

        self.assertContains(response, 'успешно изменен', status_code=200)

        all_news = News.objects.all()
        self.assertEquals(len(all_news), 1)
        only_news = all_news[0]
        self.assertEquals(only_news.title, 'Моя вторая новость')
        self.assertEquals(only_news.announcement, 'Анонс второй новости')
        self.assertEquals(only_news.text, 'Текст второй новости')
Example #23
0
    def test_news_page(self):
        category = Category()
        category.name = 'Экономика'
        category.description = 'Новости экономики'
        category.slug = 'economy'
        category.save()

        news = News()
        news.title = 'Моя первая новость'
        news.text = 'Текст первой новости'
        news.pub_date = timezone.now()
        news.category = category
        news.save()

        all_news = News.objects.all()
        self.assertEquals(len(all_news), 1)

        response = self.client.get('/news/' + str(news.id) + '/')
        self.assertContains(response, news.title, status_code=200)
        self.assertContains(response, news.text)
        self.assertContains(response, news.pub_date.year)
        # выдает на англ и сравнивает с русским - не отрабатывает self.assertContains(response, news.pub_date.strftime('%b'))
        self.assertContains(response, news.pub_date.day)
        self.assertContains(response, news.category.name)
Example #24
0
    def handle(self, *args, **options):

        faker = Faker()

        # Create categories
        if Category.objects.all().count() == 0:
            Category.objects.bulk_create([
                Category(name='Politics',
                         slug='politics',
                         seo_title='Politics - read online on Blog-News',
                         seo_description='Last news of Politics '
                         'from all world. '
                         'Read online on Blog-News.'),
                Category(name='Finance',
                         slug='finance',
                         seo_title='Finance - read online on Blog-News',
                         seo_description='Last news of Finance '
                         'from all world. '
                         'Read online on Blog-News.'),
                Category(name='Economics',
                         slug='economics',
                         seo_title='Economics - read online on Blog-News',
                         seo_description='Last news of Economics '
                         'from all world. '
                         'Read online on Blog-News.'),
                Category(name='Sports',
                         slug='sports',
                         seo_title='Sports - read online on Blog-News',
                         seo_description='Last news of Sports '
                         'from all world. '
                         'Read online on Blog-News.')
            ])

        all_categories = Category.objects.all()
        list_category_name = [category.name for category in all_categories]

        all_users_is_staff = User.objects.all()
        list_all_users_is_staff = [
            user.username for user in all_users_is_staff if user.is_staff
        ]

        for new_post in range(options['len']):
            post = Post()
            post.title = faker.sentence(nb_words=5,
                                        variable_nb_words=False).replace(
                                            '.', '')

            post.slug = f'{post.title}'.lower().replace(' ', '-').replace(
                '.', '')  # noqa
            post.article = faker.text()
            # random Category
            post.category = Category.objects.get(
                name=choice(list_category_name))
            # random user is_staff
            post.author = User.objects.get(
                username=choice(list_all_users_is_staff))
            post.seo_title = f'{post.title} | ' \
                             f'Read online | Blog news'.replace('.', '')
            post.seo_description = f'{post.title} | Blog news.'
            post.save()

            # list for random posts
            all_posts = Post.objects.all()
            list_post_name = [post.id for post in all_posts]
            # create comments
            comment = Comment()
            comment.text = faker.text()
            # random Post
            comment.for_post = Post.objects.get(id=choice(list_post_name))
            # random user is_staff
            comment.author = User.objects.get(
                username=choice(list_all_users_is_staff))
            comment.save()
Example #25
0
def editView(request, id):
	q = Category.objects.all()
	obj = Category(name="smileyz")
	obj.save()
	context = {"object": obj}
	return render(request,'edit.html', context)
Example #26
0
 def test_does_slug_field_work(self):
     from news.models import Category
     cat = Category(name='how do i create a slug in django')
     cat.save()
     self.assertEqual(cat.slug,'how-do-i-create-a-slug-in-django')