Ejemplo n.º 1
0
def seed_from_fake():
    "This seeds a DB with fake text, using the faker"
    # create a fake factory
    fake = Factory.create()

    # print is as sanity check
    print(fake.text())

    # open or make text file
    text_file = open("Output.txt", "w")

    # 50 times
    for i in range(50):
        # make some fake text
        fake_text = fake.text() # this just gives stupid text 
        # # print fake text
        # print(fake_text[:49])
        # # print seperator
        # print("_____________")
        # make new post

        # split the text up to make a title and post 
        title = fake_text[:49]
        text = fake_text

        post = Post(title=fake_text, text=text)
        post.save()
Ejemplo n.º 2
0
def news_update(request, id):
    if request.method=="GET":
        post = get_object_or_404(Post, id=id)
        post_form = PostForm(instance=post)
        update = {'edit':True}
        return render_to_response('news_form.html', {'form': post_form, 'update':update}, context_instance=RequestContext(request))
    #Manage POST requests.    
    else:
        post_form = PostForm(request.POST)
        if post_form.is_valid():
            pf = post_form.save(commit=False)
            if pf.post or pf.url :
                post = Post(id=id)
                post.name, post.url, post.post = pf.name, pf.url, pf.post
                post.save()
                return HttpResponseRedirect("/news/"+ str(id)+"/")
            else:
                form_errors = {"Empty Fields - You at least need to have filled the URL or Post Field."} 
                return render_to_response('news_form.html',
                    {'form': post_form,'form_errors': form_errors}, 
                    context_instance=RequestContext(request))
        else:
            return render_to_response('news_form.html',
                    {'form': post_form,'form_errors': post_form.errors}, 
                    context_instance=RequestContext(request))
Ejemplo n.º 3
0
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
Ejemplo n.º 4
0
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
Ejemplo n.º 5
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
Ejemplo n.º 6
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()
Ejemplo n.º 7
0
def seed_from_file():
    "This seeds the db from a tab seperated file without using csv reader"
    # open text file for reading
    with open("posts/Output.txt", "r") as seed_file:

    # iterate across each line
        for line in seed_file:
            # split on tab
            split = line.split("  ")
            # first part is title
            title = split[0].strip(' \n')
            # second part is text
            text = split[1].strip(' \n')
            # make post object with text and title
            post = Post(title=title, text=text)
            # save to db
            post.save()
Ejemplo n.º 8
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)
Ejemplo n.º 9
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('')
Ejemplo n.º 10
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('')
Ejemplo n.º 11
0
def set_up():
    post = Post(heading='Apply for membership',
                body="It's worth it"
                )
    post.save()
Ejemplo n.º 12
0
			SELECT ?title ?content
			WHERE {
				?post a sioc:Post ;
					  dcterms:title ?title ;
					  sioc:content ?content .
			}
			"""
	query = Parse(query)

	posts = []
	for row in graph.query(query):
		posts.append((row[0], row[1]))

	return posts

posts = getPosts(graph)

##################

from news.models import Post

print Post.objects.all() 

for post in posts:
	p = Post(title=post[0], content=post[1])
	p.save()

print Post.objects.all()


Ejemplo n.º 13
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()
Ejemplo n.º 14
0
 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,
                 link=link,
                 fivelinesummary=fivelinesummary,
                 tenlinesummary=tenlinesummary,
                 sum_basic=sum_basic,
                 LSA=LSA,
                 textrank=textrank,
                 lexrank=lexrank,