예제 #1
0
    def test_creating_a_new_post(self):
        """
        Testing the Posts creation in Blog application_
        """
        post=Post()
        post.body='Test post'
        post.created=timezone.now()

        # now i'm gonna check if i can save this post
        post.save()

        # check if post is in database
        all_posts_in_database=Post.objects.all()
        self.assertEquals(len(all_posts_in_database), 1)
        only_post_in_database=all_posts_in_database[0]
        self.assertEquals(only_post_in_database, post)

        #check the data in post
        self.assertEquals(only_post_in_database.body, 'Test post')
        self.assertEquals(only_post_in_database.created.date(), post.created.date())

        self.browser.get(self.live_server_url + '/blog/')

        # She sees the familiar 'Django administration' heading
        body = self.browser.find_element_by_tag_name('body')
        self.assertIn('Blog', body.text)
예제 #2
0
def edit(request, post_id):
    if request.method == 'POST':
        title = request.POST['title']
        body = request.POST['body']

        post = Post.get_by_id(int(post_id))
        post.title = title
        post.body = body
        post.updated_at = datetime.now()
        post.is_edited = True
        post.put()

        title_for_url = post.title_for_url()
        year = post.created_at.year
        month = post.created_at.month
        redirect_uri = '/' + str(year) + '/' + str(month) + '/' + str(title_for_url) + '/' + str(post_id)

        return HttpResponseRedirect(redirect_uri)
    else:
        post = Post.get_by_id(int(post_id))

        if post.active:
            return render_to_response('edit.html',
                                      {'post': post, 'post_id': post_id},
                                      context_instance=RequestContext(request))
        else:
            return HttpResponseRedirect('/')
예제 #3
0
파일: main.py 프로젝트: yablochkin/homepage
def add():
    form = PostForm(request.form)
    if request.method == "POST" and form.validate():
        post = Post(title=form.title.data, slug=form.slug.data, content=form.content.data)
        post.put()
        return redirect(post.get_url())
    return render_template("form.html", form=form, section="add")
예제 #4
0
    def test_link_to_post_present(self):
        post = Post(title=u"Post 1")
        post.put()

        response = self.client.get(self.url)

        self.assertContains(response, post.url)
예제 #5
0
파일: views.py 프로젝트: skols/flask_blog
def post():
    form = PostForm()
    if form.validate_on_submit():
        image = request.files.get('image')
        filename = None
        try:
            filename = uploaded_images.save(image)
        except:
            flash("The image was not uploaded.")
        if form.new_category.data:
            new_category = Category(form.new_category.data)
            db.session.add(new_category)
            db.session.flush()
            category = new_category
        elif form.category.data:
            category_id = form.category.get_pk(form.category.data)
            category = Category.query.filter_by(id=category_id).first()
        else:
            category = None
        blog = Blog.query.first()
        # BE SURE TO INCLUDE first()
        author = Author.query.filter_by(username=session['username']).first()
        title = form.title.data
        body = form.body.data
        slug = slugify(title)
        post = Post(blog, author, title, body, category, filename, slug)
        post.save()
        return redirect(url_for('article', slug=slug))
        
    return render_template('blog/post.html', form=form, action="new")
예제 #6
0
파일: views.py 프로젝트: joshcai/website
def newpost(request):
	if 'logged_in_blog' in request.session and request.session['logged_in_blog']:
		tags = Tag.objects.all()
		if request.method == 'POST':
			if request.POST['subject'] and request.POST['content']:
				d = datetime.datetime.now()
				p = Post(subject=request.POST['subject'], content=request.POST['content'], content_rendered=render_post(request.POST['content']), date=d, date_str=d.strftime('%B %d, %Y'))
				p.save()
				for tag in tags:
					if tag.descript in request.POST:
						p.tags.add(tag)
				return HttpResponseRedirect(reverse('blog:index'))
			else:
				context={
					'subject': request.POST['subject'],
					'content': request.POST['content'],
					'error_message': "Please fill in all fields<br />",
					'url': reverse('blog:newpost'),
					'title': "New Post",
					'request': request,
					'tags': tags,
					'nav': 'blog',
				}
				return render(request, 'blog/newpost.html', context)
		return render(request, 'blog/newpost.html', {'url': reverse('blog:newpost'), 'title': "New Post", 'request': request, 'tags': tags, 'nav': 'blog',})
	else:
		return HttpResponseRedirect(reverse('blog:index'))
예제 #7
0
def page(page_number):
    if page_number <= 0:
        abort(404)

    n = 9

    query = Post.where(published=True).orderby(
        Post.datetime, desc=True).limit(n, offset=n * (page_number - 1)
                                        ).select()
    results = query.execute()
    count = results.count

    if count < 0:  # no posts
        abort(404)

    query = Post.where(published=True).select(fn.count(Post.id))
    result = query.execute()
    func = result.one()
    total_count = func.count

    is_first_page = True if page_number == 1 else False
    is_last_page = True if n * page_number >= total_count else False

    posts = tuple(results.all())

    page = dict(
        number=page_number,
        posts=posts,
        first=is_first_page,
        last=is_last_page
    )
    return render_public('page.html', page=page)
예제 #8
0
 def test_failed_create_post(self):
     new_post = Post()
     new_post.title = 'hello'
     new_post.content = 'world'
     with transaction.atomic():
         with self.assertRaises(IntegrityError):
             new_post.save() # 장고가 자동으로 만드는 test용 DB에 저장됨
예제 #9
0
    def test_create_posts(self):
        p = Post()
        p.title = "Hello world"
        p.content = "blah blah blah"
        p.save()

        self.assertEqual(Post.objects.count(), 1)
예제 #10
0
파일: views.py 프로젝트: gvidon/blombum
def post_detail(request, object_id):
    post = get_object_or_404(WPost, pk=object_id)
    try:
        imported = Post.objects.get(slug=post.slug)
    except Post.DoesNotExist:
        imported = None
    if request.method == 'POST' and not imported:
        settings.ENABLE_PINGBACK = False
        # TODO: remove hardcoded author
        author = User.objects.get(pk=1)
        new = Post(
            author=author,
            name=post.title,
            slug=post.slug,
            text=post.content,
            date=post.date,
            enable_comments = post.comment_status == 'open',
            tags = ' '.join(c.name for c in post.categories.all()),
            )
        new.save()
        request.user.message_set.create(message="Post #%s with slug %s added" % (post.id, post.slug))
        for c_id in request.POST.getlist('comment'):
            cmt = _save_comment(c_id, new, post)
            request.user.message_set.create(message="Comment #%s from %s has been added" % (cmt.id, cmt.user))
        return HttpResponseRedirect(post.get_absolute_url())
    return {'object': post, 'imported': imported}
예제 #11
0
	def test_was_published_recently_with_recent_post(self):
		"""
		was_published_recently() should return True for posts whose pub_date
		is within the last day
		"""
		recent_post = Post(pub_date=timezone.now() - datetime.timedelta(hours=1))
		self.assertEqual(recent_post.was_published_recently(), True)
예제 #12
0
def writeNewPost(request):
    if not request.POST:
        return render_to_response('templates/writeNewPost.html', context_instance=RequestContext(request))
    response_dict = {}
    post = request.POST.get('post', False)
    author = request.POST.get('author', False)
    datePosted = datetime.now()
    dateEdited = datePosted
    title = request.POST.get('title', False)

    post = parseLinks(post)

    response_dict.update({'post': post, 'author': author, 'title': title})
    #check for errors and bad input here...
    if post and author and title:
        newPost = Post(blogPost = post, pub_date = datePosted, author = author, 
                       title = title, wasEdited = False, dateEdited = dateEdited)
        newPost.save()
        return HttpResponseRedirect('/')
    
    #if there were any errors,, then...
    else:
        if not post:
            response_dict.update({'isErrorPost': True})
        if not author:
            response_dict.update({'isErrorAuthor': True})
        if not title:
            response_dict.update({'isErrorTitle': True})

    return render_to_response('templates/writeNewPost.html', response_dict, 
                              context_instance=RequestContext(request))
예제 #13
0
	def test_was_published_recently_with_old_post(self):
		"""
		was_published_recently() should return False for posts whose pub_date
		is older than 1 day
		"""
		old_post = Post(pub_date=timezone.now() - datetime.timedelta(days=30))
		self.assertEqual(old_post.was_published_recently(), False)
예제 #14
0
	def test_was_published_recently_with_future_post(self):
		"""
		was_published_recently() should return False for posts whose
		pub_date is in the future
		"""
		future_post = Post(pub_date=timezone.now() + datetime.timedelta(days=30))
		self.assertEqual(future_post.was_published_recently(), False)
예제 #15
0
파일: views.py 프로젝트: mrfuxi/gae-blog
    def post(self, request, slug=None, *args, **kwargs):
        if not users.is_current_user_admin():
            return HttpResponseForbidden()

        post = self.get_object()
        if not post and slug:
            raise Http404()

        form = PostForm(request.POST)
        if not form.validate():
            error_msg = [
                "There are problems with the form:",
            ]
            error_msg = itertools.chain(error_msg, *form.errors.values())

            return HttpResponseBadRequest("<br/>".join(error_msg))

        # title has to exit at that point due to the validators
        new_slug = slugify(form.data["title"])
        if slug is None and Post.get_by_slug(new_slug):
            return HttpResponseBadRequest("Post with this title alread exit")

        created = False
        if not post:
            created = True
            post = Post()

        form.populate_obj(post)
        post.author = users.get_current_user().nickname()
        post.put()

        context = self.get_context_data(post=post, short=created)
        return self.render_to_response(context)
예제 #16
0
def newannounce(request):
	if 'user' in request.session:
		if request.method == 'POST':
			if request.POST['subject'] and request.POST['content']:
				d = datetime.datetime.now()
				p = Post(subject=request.POST['subject'],subject_rendered=render_subject(request.POST['subject'], request.POST['link']), 
					content=request.POST['content'], content_rendered=render_post(request.POST['content']), 
					date=d, date_str=d.strftime('%B %d, %Y'),
					author=get_user(request),
					link=request.POST['link'],
					kind='announce'
					)
				p.save()
				return HttpResponseRedirect(reverse('blog:index'))
			else:
				context={
					'subject': request.POST['subject'],
					'content': request.POST['content'],
					'error_message': "Please fill in all fields",
					'request': request,
					'url': reverse('blog:newannounce'),
				}
				return render(request, 'blog/newpost.html', context)
		return render(request, 'blog/newpost.html', {'request': request, 'url': reverse('blog:newannounce')})
	else:
		return HttpResponseRedirect(reverse('blog:index'))
예제 #17
0
def editpost(request, blog_id):
    if not request.POST:
        blogPost = Post.objects.get(pk=blog_id)
        return render_to_response('templates/editpost.html', {'blogPost': blogPost}, 
                                  context_instance=RequestContext(request))
    response_dict = {}
    post = request.POST.get('post', True)
    author = request.POST.get('author', False)
    title = request.POST.get('title', False)
    dateEdited = datetime.now()

    response_dict.update({'post': post, 'author': author, 'title': title})
    #check for errors and bad input here...
    if post and author and title:
        #save the input here
        blogPost = Post.objects.get(pk=blog_id)
        blogPost = Post(pk = blog_id, blogPost = post, pub_date = blogPost.pub_date, 
                        author = author, title = title, wasEdited = True, dateEdited = dateEdited )
        blogPost.save()
        return HttpResponseRedirect('/')    

    #if there were any errors, then...
    else:
        if not post:
            response_dict.update({'isErrorPost': True})
        if not author:
            response_dict.update({'isErrorAuthor': True})
        if not title:
            response_dict.update({'isErrorTitle': True})

    return render_to_response('templates/editpost.html', response_dict, 
                              context_instance=RequestContext(request))
예제 #18
0
    def test_delete_post(self):
        # Create the post
        post = Post()
        post.title = 'My first post'
        post.slug = 'my-first-post'
        post.excerpt = 'This is the excerpt'
        post.text = 'This is my first blog post'
        post.pub_date = timezone.now()
        post.post_color = 'orange'
        post.tags = 'test-tag'
        post.save()

        # Check new post saved
        all_posts = Post.objects.all()
        self.assertEquals(len(all_posts), 1)

        # Log in
        self.client.login(username='******', password="******")

        # Delete the post
        response = self.client.post('/admin/blog/post/1/delete/', {
            'post': 'yes'
        }, follow=True)
        self.assertEquals(response.status_code, 200)

        # Check deleted successfully
        self.assertTrue('deleted successfully' in response.content)

        # Check post amended
        all_posts = Post.objects.all()
        self.assertEquals(len(all_posts), 0)
예제 #19
0
 def test_post_detail(self):
     post = Post(author=self.user, title='Test title', text='Test text')
     post.save()
     response = self.client.get('/post/' + str(post.id) + "/", data={'pk': post.pk})
     self.assertTemplateUsed('blog/post_detail.html')
     self.assertEqual(response.status_code, 200)
     self.assertEqual(response.context['post'], post)
예제 #20
0
 def save(self, commit=True):
     title = self.cleaned_data['title']
     content = self.cleaned_data['content']
     post = Post(title=title, content=content)
     if commit:
         post.save()
     return post
예제 #21
0
def post_edit(request, track_id=None, point_id=None):
    if track_id is not None:
        track = get_object_or_404(Track, id=track_id)
        url_name = 'manager_tracks'
    elif point_id is not None:
        track = get_object_or_404(Point, id=point_id)
        url_name = 'manager_points'
    else:
        return HttpResponseNotFound()
    if track.post is None:
        post = Post(title=track.name,
                    text='')
        post.save()
        track.post = post
        track.save()
    else:
        post = track.post
    if request.method == "POST":
        form = PostForm(request.POST, instance=post)
        if form.is_valid():
            form.save()
            if request.POST.get('submit', 'to_current_page') == 'to_section':
                return HttpResponseRedirect(reverse(url_name))

    else:
        form = PostForm(instance=post)
    title = u'Редактирование "%s"' % post.title

    return render_to_response('post_edit.html',
                              {'form': form,
                               'title': title,
                               'back_url': reverse(url_name)
                               },
                              RequestContext(request))
예제 #22
0
def create(request):
	title = request.POST['title']
	content = request.POST['content']
	date = timezone.now()
	post = Post(title=title, author=request.user, content=content, date=date)
	post.save()
	return HttpResponseRedirect(reverse('blog:detail', args=(post.id,)))
예제 #23
0
  def process(self):
    self.log("Starting to process key: " + self.key)
    data = self._getData()
    post = self._getExistingPost()

    if not post:
      self.log("Post has not been seen before, creating new one.")
      post = Post()
      post.date_published = self._getPublishedDate()
      post.key = ndb.Key("Post", self.subkey)
      post.slug = data.get('slug', self.slug)
      post.published = True
    else:
      self.log("Post has been seen before, updating existing one.")

    # As a precaution, if the post has a status that is draft, ignore it.
    if data.get('status'):
      if data['status'] == "draft":
        self.log("Caught post in Draft mode, ending processing.")
        return

    post.title = data['title']
    post.body = self._renderBody(data.content)
    post.frontmatter = data.to_dict()
    post.put()

    return post.body
예제 #24
0
    def test_post_by_slug(self):
        post = Post(title=u"New post")
        post.put()

        by_slug = Post.get_by_slug("new-post")

        self.assertEquals(by_slug, post)
예제 #25
0
파일: views.py 프로젝트: yhfyhf/Django-Blog
def Index(request):
	if request.POST:
		if not request.user.is_authenticated():
			return redirect('/login/')
		form = PostForm(request.POST)
		if form.is_valid():
			submitted_title = request.POST['title']
			submitted_content = request.POST['content']
			submmited_tags = request.POST['tags']
			pub_date = datetime.now()
			new_post = Post(title=submitted_title, 
							content=submitted_content, pub_date=pub_date)
			new_post.save()
			submmited_tags = submmited_tags.replace(',', ',')
			tags = submmited_tags.split(',')
			for tag in tags:
				tag.strip()
				new_tag = Tag(post=new_post, name=tag)
				new_tag.save()
	""" request.GET """
	ctx = {}
	posts = Post.objects.all().order_by('-pub_date')
	tags = Tag.objects.all()
	post_form = PostForm()
	ctx.update(csrf(request))
	ctx['posts'] = posts
	ctx['tags'] = tags
	ctx['form'] = post_form
	return render(request, 'blog/index.html', ctx)
 def handle(self, *args, **options):
     for filename in args:
         self.stdout.write("Reading {}".format(filename))
         defaults = parse(filename)
         categories = defaults.pop('categories')
         slug = defaults.pop('slug')
         #print(title)
         #print(categories)
         #pprint(defaults)
         # Implement update_or_create only available when 1.7 is out.
         try:
             post = Post.objects.get(slug=slug)
             for key, value in defaults.items():
                 setattr(post, key, value)
             post.save()
             self.stdout.write("Updated article {}".format(post.title))
         except Post.DoesNotExist:
             defaults.update({'slug': slug})
             post = Post(**defaults)
             post.save()
             self.stdout.write("Created article {}".format(post.title))
         for cat_name in categories:
             try:
                 post.categories.get(name=cat_name)
                 self.stdout.write("Found category {}.".format(cat_name))
             except Category.DoesNotExist:
                 try:
                     category = Category.objects.get(name=cat_name)
                     post.categories.add(category)
                     self.stdout.write(
                         "Assigned category {}.".format(cat_name)
                         )
                 except Category.DoesNotExist:
                     post.categories.create(name=cat_name)
                     self.stdout.write(
                         "Created category {}".format(cat_name)
                         )
         # Now do the redirects.
         # the Redirect model has an old_path, a new_path, and a site_id.
         # use settings.SITE_ID
         old_path = "/blogue/" + post.slug + ".html"
         new_path = "/blogue/" + post.slug + "/"
         defaults = {
             'site_id': settings.SITE_ID,
             'old_path': old_path,
             }
         try:
             redirect = Redirect.objects.get(**defaults)
             redirect.new_path = new_path
             redirect.save()
             self.stdout.write(
                 "Updated redirect {} ==> {}".format(old_path, new_path)
                 )
         except Redirect.DoesNotExist:
             defaults.update({'new_path': new_path})
             redirect = Redirect(**defaults)
             redirect.save()
             self.stdout.write(
                 "Created redirect {} ==> {}".format(old_path, new_path)
                 )
예제 #27
0
    def test_single(self):
        # Create the post
        post = Post()
        post.title = 'My first post'
        post.slug = 'my-first-post'
        post.excerpt = 'This is the excerpt'
        post.text = 'This is my first blog post'
        post.pub_date = timezone.now()
        post.tags = 'test-tag'
        post.post_color = 'orange'
        post.save()

        # Check new post saved
        all_posts = Post.objects.all()
        self.assertEquals(len(all_posts), 1)

        # Fetch the single post
        response = self.client.get('/blog/my-first-post/')
        self.assertEquals(response.status_code, 200)

        # Check the post title is in the response
        self.assertTrue(post.title in response.content)

        # Check the text is in the response
        self.assertTrue(post.text in response.content)

        # Check the post date is in the response
        self.assertTrue(str(post.pub_date.year) in response.content)
        self.assertTrue(post.pub_date.strftime('%b') in response.content)
        self.assertTrue(str(post.pub_date.day) in response.content)
예제 #28
0
def show_index(request):
    user = User.objects.get(username='******')
    context = {}

    if request.method == 'POST':
        form = PostForm(request.POST)
        context['form'] = form
        #import pdb;pdb.set_trace()
        if form.is_valid():
            title = form.cleaned_data['title']
            text = form.cleaned_data['text']
            post = Post(title=title, text=text)
            post.author = user
            post.save()

            return redirect(reverse('posts-index'))
    else:
        form = PostForm()
        context['form'] = form

    posts = Post.objects.all()
    context['posts'] = posts

    #return HttpResponse(json.dumps(data), content_type='application/json')
    return render(request, 'posts.html', context)
예제 #29
0
 def test_failed_save_post_by_model(self):
     '''Post 모델을 이용해 데이터를 저장할 때 실패하는 경우에 대한 테스트
     '''
     new_post = Post()
     new_post.content = 'fail'
     with transaction.atomic():
         with self.assertRaises(IntegrityError):
             new_post.save()
예제 #30
0
 def save(self,like):
     p = Post(title=like.title,
              created=datetime.datetime.fromtimestamp(int(like.created_utc)),
              external_link=like.permalink,
              post_type=self.pt,
              external_data=jsonpickle.encode(like)
     )
     p.save()
예제 #31
0
    def content_html(self):
        '''直接渲染模板'''
        from blog.models import Post
        from comment.models import Comment

        result = ''
        if self.display_type == self.DISPLAY_HTML:
            result = self.content
        elif self.display_type == self.DISPLAY_LATEST:
            context = {
                'posts':Post.latest_postlist(Post)
            }
            result = render_to_string('sidebar_posts.html',context)
        elif self.display_type == self.DISPLAY_HOT:
            context = {
                'posts': Post.host_post(Post)
            }
            result = render_to_string('sidebar_posts.html', context)
        elif self.display_type == self.DISPLAY_COMMENT:
            context = {
                'comments': Comment.objects.filter(status=Comment.STATUS_NORMAL)
            }
            result = render_to_string('sidebar_comments.html', context)
        return result
예제 #32
0
def new_post(request):
    if request.method == 'POST':
        print request
        # create a form instance and populate it with data from the request
        form = BlogForm(request.POST)
        # check if it is valid
        if form.is_valid():
            # process data and redirect to a new URL
            title = form.cleaned_data['title']
            description = form.cleaned_data['description']
            content = form.cleaned_data['content']
            new = Post(title=title,
                       content=content,
                       description=description,
                       published=form['published'],
                       slug=slugify(unicode(title)))
            new.save()
            return HttpResponseRedirect('/blog/')
    # GET or other methods, create a blank form
    else:
        print "GET HERE"
        form = BlogForm()
        print form
    return render(request, 'blog/new.html', {'form': form})
예제 #33
0
    def content_html(self):
        """直接渲染模板"""
        from blog.models import Post  # 避免循环引用
        from comment.models import Comment

        result = ""
        if self.display_type == self.DISPLAY_HTML:
            result = self.content
        elif self.display_type == self.DISPLAY_LATEST:
            context = {"posts": Post.latest_posts()}
            result = render_to_string("config/blocks/sidebar_posts.html",
                                      context)
        elif self.display_type == self.DISPLAY_HOT:
            context = {"Posts": Post.hot_posts()}
            result = render_to_string("config/blocks/sidebar_posts.html",
                                      context)
        elif self.display_type == self.DISPLAY_COMMENT:
            context = {
                "comments":
                Comment.objects.filter(status=Comment.STATUS_NORMAL)
            }
            result = render_to_string("config/blocks/sidebar_comments.html",
                                      context)
        return result
예제 #34
0
파일: post.py 프로젝트: CoCongV/Blog
 def patch(self, post_id):
     # 修改文章
     args = post_parser.parse_args()
     post = Post.get_or_404(post_id)
     if g.current_user != post.author and not g.current_user.can(
             Permission.ADMINISTER):
         raise Forbidden(description="Insufficient permissions")
     post.update(title=args.title,
                 body=args.content,
                 tags=args.tags,
                 draft=args.draft)
     return {
         'url': url_for('post.postview', post_id=post.id),
         'post_id': post.id
     }
예제 #35
0
    def content_html(self):
        """ 直接渲染模板 """
        from blog.models import Post  # 避免循环引用
        from comment.models import Comment

        result = ''
        if self.display_type == self.DISPLAY_HTML:
            result = self.content
        elif self.display_type == self.DISPLAY_LATEST:
            context = {'posts': Post.latest_posts(with_related=False)[:5]}
            result = render_to_string('config/blocks/sidebar_posts.html',
                                      context)
        elif self.display_type == self.DISPLAY_HOT:
            context = {'posts': Post.hot_posts()[:5]}
            result = render_to_string('config/blocks/sidebar_posts.html',
                                      context)
        elif self.display_type == self.DISPLAY_COMMENT:
            context = {
                'comments':
                Comment.objects.filter(status=Comment.STATUS_NORMAL)[:5]
            }
            result = render_to_string('config/blocks/sidebar_comments.html',
                                      context)
        return result
예제 #36
0
def new_post():
    form = PostForm()
    if form.validate_on_submit():
        post = Post(category=form.category.data,
                    title=form.title.data,
                    content=form.content.data,
                    author=current_user)
        db.session.add(post)
        db.session.commit()
        flash(f'Posted!', 'success')
        return redirect(url_for('home'))
    return render_template('create_post.html',
                           title='New Post',
                           form=form,
                           legend='New Post')
예제 #37
0
    def content_html(self):
        #直接在模型层渲染模板,避免view层过于臃肿
        #这部分逻辑有点没懂,render_to_string()返回的是什么?
        from blog.models import Post
        from comment.models import Comment

        result = ''
        if self.display_type == self.DISPLAY_HTML:
            result = self.content
        elif self.display_type == self.DISPLAY_LATEST:
            context = {'posts': Post.latest_posts()}
            result = render_to_string('config/blocks/sidebar_posts.html',
                                      context)
        elif self.display_type == self.DISPLAY_HOT:
            context = {'posts': Post.hot_posts()}
            result = render_to_string('config/blocks/sidebar_posts.html',
                                      context)
        elif self.display_type == self.DISPLAY_COMMENT:
            context = {
                'posts': Comment.objects.filter(status=Comment.STATUS_NORMAL)
            }
            result = render_to_string('config/blocks/sidebar_comments.html',
                                      context)
        return result
예제 #38
0
class PostDetailView(CommonViewMixin, DetailView):
    queryset = Post.latest_post()
    template_name = 'blog/detail.html'
    context_object_name = 'post'
    pk_url_kwarg = 'post_id'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context.update({
            'comment_form':
            CommentFor,
            'comment_list':
            Comment.get_by_target(self.request.path),
        })
        return context
예제 #39
0
def seed():
    content = """
        Lorem ipsum dolor sit amet, consectetur adipisicing elit,
        sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
        Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris
        nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in
        reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
        pariatur. Excepteur sint occaecat cupidatat non proident,
        sunt in culpa qui officia deserunt mollit anim id est laborum.
        """

    for i in range(25):
        post = Post(title="Test Post #{}".format(i), content=content)
        session.add(post)
    session.commit()
예제 #40
0
    def content_html(self):
        from blog.models import Post
        from comment.models import Comment

        result = ''
        if self.display_type == self.display_html:
            result = self.content
        elif self.display_type == self.display_latest:
            context = {'posts': Post.latest_posts()}
            result = render_to_string('config/sidebar_post.html',
                                      context=context)
        elif self.display_type == self.display_hot:
            context = {'posts': Post.hot_posts()}
            result = render_to_string('config/sidebar_post.html',
                                      context=context)
        elif self.display_type == self.display_comment:
            context = {
                'comments':
                Comment.objects.filter(
                    status=Comment.status_normal).select_related('target')
            }
            result = render_to_string('config/sidebar_comment.html',
                                      context=context)
        return result
예제 #41
0
    def get_sidebar_content_html(self):
        """”
            直接渲染模板;
            将导入语句写入函数中防止循环引用,因为bog和comment app的models中将来也有可能引用config app的models
        """
        from blog.models import Post
        from comment.models import Comment

        result = ''
        if self.display_type == self.DISPLAY_HTML:
            result = self.content
        elif self.display_type == self.DISPLAY_LATEST:
            context = {"posts": Post.get_lastest_post()}
            result = render_to_string("config/blocks/sidebar_posts.html",
                                      context=context)
        elif self.display_type == self.DISPLAY_HOT:
            context = {"posts": Post.get_hot_posts().only("id", "title")}
            result = render_to_string("config/blocks/sidebar_posts.html",
                                      context=context)
        elif self.display_type == self.DISPLAY_COMMENT:
            context = {"comments": Comment.get_all()}
            result = render_to_string("config/blocks/sidebar_comments.html",
                                      context=context)
        return result
예제 #42
0
def createBlog():
    blog_tag = BlogTag.objects.create(name="tag11")
    blog_category = BlogCategory.objects.create(name="cat11")
    user = User.objects.create_user("alamin11", "*****@*****.**")
    post = Post(title="titlexyz", author=user, post_type="blog", text="text")
    post.save()
    post.tag.add(blog_tag)
    post.category.add(blog_category)
    post.save()
    return post, blog_tag, blog_category
예제 #43
0
    def test_create_post(self):

        self.assertEquals(0, Post.objects.count())

        post = Post()
        post.title = "First Post Evvvveeeerrrr!"
        post.content = "Good Morning!"
        post.save()

        self.assertEquals(1, Post.objects.count())
예제 #44
0
파일: base.py 프로젝트: xue000/Blog
    def setUp(self):
        app = create_app('testing')
        self.context = app.test_request_context()
        self.context.push()
        self.client = app.test_client()
        self.runner = app.test_cli_runner()

        db.create_all()
        Role.init_role()

        admin_user = User(email='*****@*****.**',
                          name='Admin',
                          username='******')
        admin_user.set_password('123')
        admin_user.set_role()
        normal_user = User(email='*****@*****.**',
                           name='Normal User',
                           username='******')
        normal_user.set_password('123')
        unconfirmed_user = User(
            email='*****@*****.**',
            name='Unconfirmed',
            username='******',
        )
        unconfirmed_user.set_password('123')
        locked_user = User(email='*****@*****.**',
                           name='Locked User',
                           username='******',
                           locked=True)
        locked_user.set_password('123')
        locked_user.lock()

        blocked_user = User(email='*****@*****.**',
                            name='Blocked User',
                            username='******',
                            active=False)
        blocked_user.set_password('123')

        category = Category(name='test category')
        post = Post(title='test post', body='Test post', category=category)
        comment = Comment(body='test comment body',
                          post=post,
                          author=normal_user)
        db.session.add_all([
            admin_user, normal_user, unconfirmed_user, locked_user,
            blocked_user
        ])
        db.session.commit()
예제 #45
0
def seed():
    content = []
    blog_sample_text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'
    print blog_sample_text
    for i in range(25):
        j = i * 10
        k = (i * 10) + 20
        print blog_sample_text[j:k]
        content.append(blog_sample_text[j:k])
        print content[i]

    for i in range(25):
        post = Post(title="Test Post #{}".format(i), content=content[i])
        session.add(post)
        print "i= %s" % i
    session.commit()
예제 #46
0
def open_post_page(request):
    form = PostForm()
    if request.method == "POST":
        form = PostForm(request.POST)
        if form.is_valid():
            category_ids = form.cleaned_data["categories"]
            if category_ids:
                post = Post(
                    title=form.cleaned_data["title"],
                    body=form.cleaned_data["body"],
                )
                postServices = BlogServices()
                postServices.insert_post(post, category_ids)
            return redirect('blog_index')
    context = {"form": form}
    return render(request, "post.html", context)
예제 #47
0
def new_post():
    form = PostForm()
    if form.validate_on_submit():
        # added author attribute to store in db
        post = Post(title=form.title.data,
                    content=form.content.data,
                    author=current_user)
        db.session.add(post)
        db.session.commit()
        flash('Your post has been created!', 'success')
        # redirecting to the MAIN package
        return redirect(url_for('main.home'))
    return render_template('create_post.html',
                           title='New Post',
                           form=form,
                           legend='New Post')
예제 #48
0
def create_post():
    form = BlogForm()

    if form.validate_on_submit():

        title = form.title.data
        text = form.text.data

        post = Post(title, text, current_user.id)
        db.session.add(post)
        db.session.commit()
        flash("Blog post created!")

        return redirect(url_for("core.index"))

    return render_template("create.html", form=form)
예제 #49
0
def newarticle():
    form = NewArticleForm()
    if form.is_submitted():
        if form.validate():
            title = form.title.data
            content = form.content.data
            post = Post(title=title, content=content, user_id=current_user.id)
            db.session.add(post)
            db.session.commit()
            flash("Article oluşturuldu", "success")
            return redirect(url_for("profil", username=current_user.username))
        else:
            flash("Hata", "danger")
    return render_template("admin/newarticle.html",
                           form=form,
                           title="newarticle")
예제 #50
0
def search():
    """View function for full-text search queries"""
    if not g.search_form.validate():
        return redirect(url_for('main.explore'))
    page = request.args.get('page', 1, type=int)
    posts, total = Post.search(g.search_form.q.data, page,
                               current_app.config['POSTS_PER_PAGE'])
    next_url = url_for('main.search', q=g.search_form.data, page=page + 1) \
        if total > page * current_app.config['POSTS_PER_PAGE'] else None
    prev_url = url_for('main.search', q=g.search_form.data, page=page - 1) \
        if page > 1 else None
    return render_template('search.html',
                           title=_("Search"),
                           posts=posts,
                           next_url=next_url,
                           prev_url=prev_url)
예제 #51
0
    def form_valid(self, form):
        csvfile = self.request.FILES['file'].read().decode(
            'utf-8').splitlines()
        file_text = csv.DictReader(csvfile)
        posts = []
        for line in file_text:
            text, raw_date = line['TEXT'], line['DATE']
            date = datetime.strptime(raw_date, '%d-%m-%Y')
            posts.append(
                Post(title=_('Без названия'),
                     text=text,
                     published=date,
                     user=self.request.user))
        Post.objects.bulk_create(posts)

        return super(PostUploadView, self).form_valid(form)
예제 #52
0
def home():
    page = request.args.get('page', 1, type=int)
    posts = Post.query.order_by(Post.date_posted).paginate(per_page=5,
                                                           page=page)
    post_form = PostForm()
    if post_form.validate_on_submit():
        post = Post(post_form.title.data, post_form.content.data,
                    current_user.id)
        db.session.add(post)
        db.session.commit()
        flash('Your Post has been published', 'success')
        return redirect(url_for('home'))
    return render_template('index.html',
                           title='Blog',
                           posts=posts,
                           post_form=post_form)
예제 #53
0
 def test_create_and_get_post_object(self):
     '''
     ToDo:
         - 初期Post数は0
         - Save後は1
         - 作成したオブジェクトとモデルから取得したPostオブジェクトが等しい。
     '''
     self.assertEquals(Post.objects.all().count(), 0)
     post = Post()
     post.title = 'sample post title'
     post.author = self.user
     post.content = 'sample post content'
     post.save()
     self.assertEqual(Post.objects.all().count(), 1)
     self.assertEqual(Post.objects.get(pk=post.pk), post)
예제 #54
0
 def test_update_post(self, post):
     p,author = post
     p.name = post_name1
     p.body = post_body1
     author.name = persion_name1
     author.email = persion_email1
     author.password = persion_pwd1
     author.save()
     p.save()
     tmp = Post.find_by_id(1)
     assert tmp == p
     assert tmp.name == post_name1
     assert tmp.body == post_body1
     assert tmp.author == author
     assert tmp.author.name == persion_name1
     assert tmp.author.email == persion_email1
     assert tmp.author.password == persion_pwd1
예제 #55
0
def post():
    form = PostForm()
    if form.validate_on_submit():
        image = request.files.get('image')
        filename = None
        try:
            filename = uploaded_images.save(image)
        except:
            flash("The image was not uploaded")

        # we are assuming we can have only category per post
        # basic order is check for new category, else check for new existing category and if none of these are presen
        if form.new_category.data:
            # checks if a new category is created or not
            new_category = Category(form.new_category.data)
            db.session.add(new_category)
            db.session.flush()
            category = new_category
        elif form.category.data:
            # check if a user seleected existing category
            category_id = form.category.get_pk(form.category.data)
            # helper function get_pk gives out the primary key
            category = Category.query.filter_by(id=category_id).first()
        else:
            # So this is condition when no category is specified
            # So we put all that in the unknown category
            # we search if there is already that category created otherwise we create it
            try:
                category_id = form.category.get_pk("Unknown")
                category = Category.query.filter_by(id=category_id).first()
            except:
                category = Category("Unknown")

        blog = Blog.query.first()
        # assuming we have only one blog
        # need to add functionality if more than one blog
        author = Author.query.filter_by(username=session['username']).first()
        title = form.title.data
        body = form.body.data
        slug = slugify(title)
        post = Post(blog, author, title, body, category, filename, slug)
        db.session.add(post)
        db.session.commit()
        return redirect(url_for('article', slug=slug))

    return render_template('blog/post.html', form=form, action="new")
예제 #56
0
def new_post():
    form = PostForm()
    if form.validate_on_submit():
        post = Post(title=form.title.data,
                    content=form.content.data,
                    author=current_user)
        db.session.add(post)
        db.session.commit()
        flash('Content has been Posted', 'success')

        return redirect(url_for('main.home'))
    else:
        pass
    return render_template('create_post.html',
                           title='New Post',
                           legend='Create Post',
                           form=form)
예제 #57
0
파일: routes.py 프로젝트: bolleyboll/Blog
def new_post():
    if is_maintenance_mode:
        return redirect(url_for('maintenance'))

    form = PostForm()
    if form.validate_on_submit():
        post = Post(title=form.title.data,
                    content=form.content.data,
                    author=current_user)
        db.session.add(post)
        db.session.commit()
        flash('Your post has been created!', 'success')
        return redirect(url_for('home'))
    return render_template('create_post.html',
                           title='New Post',
                           form=form,
                           legend='New Post')
예제 #58
0
def create_post():

    form = PostCreate()
    user = current_user
    if form.validate_on_submit():
        db.session.add(
            Post(title=form.title.data,
                 content=form.content.data,
                 author_id=user.id))
        db.session.commit()
        return redirect(url_for('main.blog'))

    return render_template(
        "post_create.html",
        form=form,
        title="Create post.",
    )
예제 #59
0
    def test_create_category(self):
        category = Category(name='Django')
        category.save()
        category2 = Category(name='Godjan')
        category2.save()
        category_count = Category.objects.count()
        assert category_count == 2

        #create posts, w title, body. add categories to post
        post = Post(title='POST1', body='testbodytext')
        post.save()
        post2 = Post(title='POST2', body='textbodytest')
        post2.save()
        post.categories.add(category)
        post.categories.add(category2)
        post2.categories.add(category)
        post2.categories.add(category2)
        post_count = Post.objects.count()
        assert post_count == 3
예제 #60
0
def post_new_form(request):
    if request.method == 'POST':
        form = PostForm(request.POST)
        print(form)
        if form.is_valid():
            post = Post()
            post.author = request.user
            post.title = form.cleaned_data["title"]
            post.text = form.cleaned_data["text"]
            post.published_date = timezone.now()
            post.save()
            # post = Post.objects.create(author = request.user, title = form.cleaned_data["title"], text = form.cleaned_data["text"],published_date = timezone.now())

            return redirect('post_detail', pk=post.pk)
        else:
            print(form.errors)
    else:
        form = PostForm()
    return render(request, 'blog/post_form.html', {'form': form})