示例#1
0
 def handle(self, *args, **options):
     self.stdout.write(self.style.SUCCESS('Start parsing ycombinator.com'))
     news = ycombinator()
     objs = [Post(**data) for data in news]
     Post.objects.bulk_create(objs, ignore_conflicts=True)
     self.stdout.write(
         self.style.SUCCESS('Get {} objects\nFinished!!!'.format(
             len(news))))
示例#2
0
文件: facebook.py 项目: TK-IT/kasse
def new_post(text):
    graph = access_page()
    o = graph.put_object(parent_object='me',
                         connection_name='feed',
                         message=text)
    p = Post(fbid=o['id'], text=text)
    p.save()
    return p
示例#3
0
    def save(self, commit=True):
        author = self.initial.get('author')
        is_approved = False

        if author.has_perm('news.post_no_premoderation'):
            is_approved = True

        post = Post(author=author,
                    title=self.cleaned_data.get('title'),
                    text=self.cleaned_data.get('text'),
                    is_approved=is_approved)

        post.save()
        return post
示例#4
0
    def import_article(self, filename, overwrite=False):
        with open(filename, 'r') as f:
            section = 0
            metadata = {}
            sections = [[], []]
            for line in f:
                line = line.strip()
                if line == '---' and section < 2:
                    section += 1
                    continue

                if section == 0:
                    # Metadata section
                    try:
                        key, value = [x.strip() for x in line.split(':', 1)]
                    except ValueError:
                        raise CommandError(
                            "Invalid metadata key:value pair: " + line)

                    metadata[key.lower()] = value

                else:
                    # Intro and readmore sections
                    sections[section - 1].append(line)

            try:
                post = Post(
                    slug=metadata['slug'],
                    publish=metadata.get('publish', timezone.now()),
                    is_visible=metadata.get('visible',
                                            'true').lower() == 'true',
                    title=metadata['title'],
                    intro='\n'.join(sections[0]),
                    readmore='\n'.join(sections[1]),
                )
            except KeyError as ke:
                raise CommandError("Metadata field " + ke.args[0] +
                                   " is required.")

            try:
                post.save()
            except IntegrityError:
                if not overwrite:
                    raise CommandError(
                        "Article exists. Use --overwrite to update.")

                post.id = Post.objects.filter(slug=post.slug).values_list(
                    'id', flat=True)[0]
                post.save()
示例#5
0
 def test_can_create_a_news_post(self):
     user = get_user_model().objects.create(username='******')
     post = Post(
         author=user,
         title="Test",
         sub_title='test',
         slug='slug',
         preview_text="preview",
         content="content",
         featured=False,
     )
     post.save()
     self.assertEqual(post.author, user)
     self.assertEqual(post.title, 'Test')
     self.assertEqual(post.sub_title, 'test')
     self.assertEqual(post.slug, 'slug')
     self.assertEqual(post.preview_text, 'preview')
     self.assertEqual(post.content, 'content')
     self.assertEqual(post.featured, False)
示例#6
0
    def post(self, request, *args, **kwargs):
        appointment = Post(
            headline=request.POST['headline'],
            text=request.POST['text'],
        )
        appointment.save()

        send_mail(
            subject=f'{appointment.headline}',
            # имя клиента и дата записи будут в теме для удобства
            message=appointment.text,  # сообщение с кратким описанием проблемы
            from_email=
            '*****@*****.**',  # здесь указываете почту, с которой будете отправлять (об этом попозже)
            recipient_list=[
                '*****@*****.**'
            ]  # здесь список получателей. Например, секретарь, сам врач и т. д.
        )

        return redirect('')
示例#7
0
 def post(self, request):
     form = PostForm(request.POST)
     if form.is_valid():
         post = form.save(commit=False)
         post.author = request.user
         all_groups = CustomGroup.objects.all()
         for group in all_groups:
             pre_moderation = getattr(group, 'pre_moderation')
             if post.author.groups.filter(name=group).exists() and \
                     pre_moderation is False:
                 post.status = Post.ACCEPTED
             else:
                 post.status = Post.IN_MODERATION
         post.save()
         return redirect('all_my_posts')
     else:
         post = Post()
         post.title = request.POST['title']
         post.description = request.POST['description']
         return render(request, 'news/create_post.html', {'form': form})
示例#8
0
    def post(self, request, *args, **kwargs):
        appointment = Post(
            text_title=request.POST['text_title'],
            text_news=request.POST['text_news'],
        )
        appointment.save()

        send_mail(
            subject=f'{appointment.text_title}',
            # имя клиента и дата записи будут в теме для удобства
            message=appointment.
            text_news,  # сообщение с кратким описанием проблемы
            from_email=
            '*****@*****.**',  # здесь указываете почту, с которой будете отправлять (об этом попозже)
            recipient_list=[
                '*****@*****.**'
            ]  # здесь список получателей. Например, секретарь, сам врач и т. д.
        )

        return redirect('')
示例#9
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()
示例#10
0
        fivelinesummary = ''.join(fivelinesummary)
        tenlinesummary = ''.join(tenlinesummary)
        sum_basic = ''.join(sum_basic)
        LSA = ''.join(LSA)
        textrank = ''.join(textrank)
        lexrank = ''.join(lexrank)
        featured_lexrank = ''.join(featured_lexrank)

        try:
            post = Post(category=category,
                        pub_date=pub_date,
                        location=location,
                        title=title,
                        content=content,
                        photo=photo,
                        link=link,
                        fivelinesummary=fivelinesummary,
                        tenlinesummary=tenlinesummary,
                        sum_basic=sum_basic,
                        LSA=LSA,
                        textrank=textrank,
                        lexrank=lexrank,
                        featured_lexrank=featured_lexrank)
            post.save()
        except ValidationError as e:
            pub_date = datetime.datetime.now()
            post = Post(category=category,
                        pub_date=pub_date,
                        location=location,
                        title=title,
                        content=content,
                        photo=photo,
示例#11
0
 def test_url_max_length(self):
     news = Post(pk=1)
     max_length = news._meta.get_field('url').max_length
     self.assertEquals(max_length, 200)
示例#12
0
 def test_url_label(self):
     news = Post(pk=1)
     field_label = news._meta.get_field('url').verbose_name
     self.assertEquals(field_label, 'Url News')
示例#13
0
 def test_name_max_length(self):
     catalog = Post(pk=1)
     max_length = catalog._meta.get_field('title').max_length
     self.assertEquals(max_length, 512)
示例#14
0
 def test_title_label(self):
     news = Post(pk=1)
     field_label = news._meta.get_field('title').verbose_name
     self.assertEquals(field_label, 'Title News')