def handle(): randomize.out("\ntags:") for i in range(50): Tag(name=randomize.string(20)).save() randomize.out('.') print "\nusers:", for i in range(5): user, created = User.objects.get_or_create( username='******' % i, email='*****@*****.**' % str(i), password='******', is_blog_author=True, first_name=u'Иван%s' % str(i), second_name=u'Иванович%s' % str(i), last_name=u'Иванов%s' % str(i), ) if created: user.save() print "\nposts" for j in range(50): post = Post( author=user, title='Post%s' % str(i), text='Post text %s' % str(i), published=True, enable_comments=True, ) post.save() if randomize.boolean(): post.tags = Tag.objects.order_by('?')[:randomize.integer(1, 6)] randomize.out('.') randomize.out('.')
def content_html(self, user_id): """ 直接在models层 渲染模版 """ from apps.blog.models import Post # 避免循环引用 from apps.comment.models import Comment result = '' if self.display_type == self.DISPLAY_HTML: result = self.content[:5] elif self.display_type == self.DISPLAY_LATEST: context = { 'posts': Post.get_latest_article(user_id=user_id)[:5] } result = render_to_string('config/blocks/sidebar_posts.html', context) elif self.display_type == self.DISPLAY_HOT: context = { 'posts': Post.get_hot_articles(user_id=user_id)[:5] } result = render_to_string('config/blocks/sidebar_posts.html', context) elif self.display_type == self.DISPLAY_COMMIT: context = { 'comments': Comment.objects.filter(status=Comment.STATUS_NORMAL, target__owner_id=user_id).select_related('owner', 'target')[:5] } result = render_to_string('config/blocks/sidebar_comments.html',context) return result
def setUp(self) -> None: super().setUp() self.tag = Tag(name='new tag') self.tag.save() self.post = Post(title='admin', body='*****@*****.**', author=self.current_user) self.post.save() self.post.tags.add(self.tag) self.post.save()
def new_post(): form = PostForm() if form.validate_on_submit(): post = Post() form.populate_obj(post) post.put() return redirect(url_for('admin.blog.index')) return render_template( 'blog/admin/post_new.html', form=form )
def test_post(self): post = Post() post.save() self.validate_response( method="post", url=f"/blog/post/{post.pk}/", expected_status_code=405, expected_view=BlogPostView, expected_template="blog/post.html", expected_view_name="blog:post", content_filters=(lambda _c: _c == b"", ), )
def create_post(req, author): out = {} out['author'] = author = get_object_or_404(User, username=author) out['back_link'] = reverse("blog_post_list", args=[author]) if req.POST: pm = Post(author=req.user) out['form'] = form = PostForm(req.POST, instance=pm) if form.is_valid(): form.save() last_post = Post.objects.filter(author=pm.author, last_post=True) if last_post: last_post = last_post[0] last_post.last_post = False last_post.save() post_ldate = Post.objects.filter(author=pm.author, published=True).order_by('-date') if post_ldate: post_ldate = post_ldate[0] post_ldate.last_post = True post_ldate.save() return HttpResponseRedirect(req.user.get_blog_absolute_url()) else: out['form'] = PostForm() return render_to_response('blog/createPost.html', out, RequestContext(req))
def test_get_existing_anon(self): placeholder = urandom(4).hex() post = Post(title=f"t_{placeholder}", content=f"c_{placeholder}") post.save() self.validate_response( url=f"/blog/post/{post.pk}/", expected_view=BlogPostView, expected_template="blog/post.html", expected_view_name="blog:post", content_filters=( lambda _c: f"t_{placeholder}".encode() in _c, lambda _c: f"c_{placeholder}".encode() in _c, lambda _c: b"<form" not in _c, ), )
def test_get(self): post = Post() post.save() user = self.create_user() client = Client() client.login(username=user.username, password=user.username) self.validate_response( client=client, url=f"/blog/post/{post.pk}/comment/", expected_status_code=405, expected_view=BlogPostView, expected_view_name="blog:post", # не проверяет тк код 405 content_filters=(lambda _c: _c == b"", ), )
def index(): posts = Post.query(Post.is_public == True).order(-Post.created) return render_template( 'blog/index.html', title=u'Новости', posts=posts )
def get_post(key_id): post = Post.retrieve_by_id(key_id) if not post: return redirect(url_for('blog.index')) return render_template( 'blog/post.html', title=u'{} - {}'.format(post.title, u'Новости'), post=post )
def test_anon(self): placeholder = urandom(4).hex() post = Post(title=f"t_{placeholder}", content=f"c_{placeholder}") post.save() self.assertEqual(0, post.comments.count()) self.validate_response( method="post", url=f"/blog/post/{post.pk}/comment/", expected_view=SignInView, expected_view_name="onboarding:sign_in", content_filters=( lambda _c: f"t_{placeholder}".encode() not in _c, lambda _c: f"c_{placeholder}".encode() not in _c, ), ) self.assertEqual(0, post.comments.count())
def test_get_existing_authed(self): placeholder = urandom(4).hex() user = self.create_user(placeholder) client = Client() client.login(username=user.username, password=placeholder) post = Post(title=f"t_{placeholder}", content=f"c_{placeholder}") post.save() self.validate_response( client=client, url=f"/blog/post/{post.pk}/", expected_view=BlogPostView, expected_template="blog/post.html", expected_view_name="blog:post", content_filters=( lambda _c: f"t_{placeholder}".encode() in _c, lambda _c: f"c_{placeholder}".encode() in _c, lambda _c: b"<form" in _c, ), )
def handle ( ): randomize.out("\ntags:") for i in range( 50 ): Tag( name = randomize.string(20) ).save() randomize.out('.') print "\nusers:", for i in range( 5 ): user, created = User.objects.get_or_create( username = '******' % i , email = '*****@*****.**' % str( i ), password = '******', is_blog_author = True, first_name = u'Иван%s' % str( i ), second_name = u'Иванович%s' % str( i ), last_name = u'Иванов%s' % str ( i ), ) if created: user.save () print "\nposts" for j in range ( 50 ): post=Post ( author = user, title = 'Post%s' % str ( i ), text = 'Post text %s' % str ( i ), published = True, enable_comments = True, ) post.save () if randomize.boolean(): post.tags = Tag.objects.order_by('?')[:randomize.integer(1, 6)] randomize.out('.') randomize.out ( '.' )
def test_post(self): placeholder = urandom(4).hex() user = self.create_user(placeholder) client = Client() client.login(username=user.username, password=user.username) post = Post(title=f"t_{placeholder}", content=f"c_{placeholder}") post.save() self.assertEqual(0, post.comments.count()) self.validate_response( client=client, method="post", url=f"/blog/post/{post.pk}/comment/", form_data={ "message": f"m_{placeholder}", "author": user.pk, "post": post.pk, }, expected_view=BlogPostView, expected_view_name="blog:post", content_filters=( lambda _c: b"<form" in _c, lambda _c: f"c_{placeholder}".encode() in _c, lambda _c: f"m_{placeholder}".encode() in _c, lambda _c: f"t_{placeholder}".encode() in _c, ), ) self.assertEqual(1, post.comments.count()) comment = post.comments.first() self.assertEqual(user, comment.author) self.assertEqual(post, comment.post) self.assertEqual(f"m_{placeholder}", comment.message)
def edit_post(key_id): post = Post.retrieve_by_id(key_id) if not post: return redirect(url_for('admin.blog.index')) if request.method == 'POST' and 'delete_post' in request.form: post.key.delete() return redirect(url_for('admin.blog.index')) form = PostForm(obj=post) if form.validate_on_submit(): form.populate_obj(post) post.put() return redirect(url_for('admin.blog.index')) return render_template( 'blog/admin/post_edit.html', form=form, post=post )
class PostAPITests(LoggedUserAPITestCase): def setUp(self) -> None: super().setUp() self.tag = Tag(name='new tag') self.tag.save() self.post = Post(title='admin', body='*****@*****.**', author=self.current_user) self.post.save() self.post.tags.add(self.tag) self.post.save() def tearDown(self) -> None: super().tearDown() self.tag.delete() self.post.delete() def get_posts(self, **kwargs): url = reverse_lazy('post-list') return self.client.get(url, kwargs, format='json') def get_post(self, slug, **kwargs): url = reverse_lazy('post-detail', kwargs={'slug': slug}) return self.client.get(url, kwargs, format='json') def post_new_post(self, title, body, tags): url = reverse_lazy('post-list') data = {"title": title, "body": body, "tags": tags} response = self.client.post(url, data, format='json') return response def test_post_new_post_with_valid_data(self): response = self.post_new_post('post title', 'post body', [self.tag.pk]) assert response.status_code == status.HTTP_201_CREATED def test_get_posts(self): response = self.get_posts() assert response.status_code == status.HTTP_200_OK def test_get_post_with_valid_slug(self): response = self.get_post(self.post.slug) assert response.status_code == status.HTTP_200_OK def test_get_post_with_fake_slug(self): response = self.get_post('fake-slug') # fake slug assert response.status_code == status.HTTP_404_NOT_FOUND
# -*- coding: utf-8 -*- import os import codecs from datetime import datetime import sys sys.path.append('../') from apps.blog.models import Post project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) fixture = eval(codecs.open(os.path.join(project_root, 'templates/content/new_blog_fixture.json'), 'r', encoding='utf-8').read()) for obj in fixture: post = Post( title=unicode(obj['title'], 'utf-8'), content=unicode(obj['content'], 'utf-8'), pub_date=datetime.strptime(obj['pub_date'], '%Y-%m-%d %H:%M:%S') ) post.save(safe=True) print 'added %s' % obj['title']
def get_latest_posts(): posts_objs = Post.query(Post.is_public == True).order(-Post.created) posts_count = posts_objs.count() posts_objs = posts_objs.fetch(4) return posts_objs, posts_count
def test_num_draft_posts(self): draft_posts = mixer.cycle(10).blend(Post, author__pk=2, status=0) published_posts = mixer.cycle(5).blend(Post, author__pk=2, status=1) total_posts = draft_posts + published_posts assert len(total_posts) == Post.objects.count(), 'Should have 15 posts in the DB' assert Post.num_draft_posts() == 10, 'Should have 10 `draft` posts in the DB'
def index(): posts = Post.query().order(-Post.created) return render_template( 'blog/admin/posts.html', posts=posts )
def index(): posts = Post.query(Post.is_public == True).order(-Post.created) return render_template("blog/index.html", title=u"Новости", posts=posts)
def get_post(key_id): post = Post.retrieve_by_id(key_id) if not post: return redirect(url_for("blog.index")) return render_template("blog/post.html", title=u"{} - {}".format(post.title, u"Новости"), post=post)