def test_model_post_creation(self): sample = Post() sample.author = 'Fadi' sample.title = 'Test Yo' sample.created_date = '2015-09-04' sample.text = 'AND NEW' sample.save() sample2 = Post() sample2.author = 'Swift' sample2.title = 'UFC Champion' sample2.created_date = '2015-09-04' sample2.text = 'AND STILL' sample2.save() saved_posts = Post.objects.all() self.assertEqual(saved_posts.count(), 2) first_sample = saved_posts[0] second_sample = saved_posts[1] self.assertEqual(first_sample.author, 'Fadi') self.assertEqual(first_sample.text, 'AND NEW') self.assertEqual(first_sample.title, 'Test Yo') #self.assertEqual(first_sample.created_date.datefield, '2015-09-04') self.assertEqual(second_sample.author, 'Swift') self.assertEqual(second_sample.text, 'AND STILL') self.assertEqual(second_sample.title, 'UFC Champion')
def test_saving_and_retrieving_items(self): my_admin = User.objects.create_superuser('myuser', '*****@*****.**', 'mypassword') c = Client() c.login(username=my_admin.username, password='******') first_item = Post() first_item.title = 'Title 1' first_item.text = 'The first (ever) list item' first_item.author = my_admin first_item.save() second_item = Post() second_item.title = 'Title 2' second_item.text = 'Item the second' second_item.author = my_admin second_item.save() saved_items = Post.objects.all() self.assertEqual(saved_items.count(), 2) first_saved_item = saved_items[0] second_saved_item = saved_items[1] self.assertEqual(first_saved_item.text, 'The first (ever) list item') self.assertEqual(second_saved_item.text, 'Item the second')
def test_tag_page(self): # Create the tag tag = Tag() tag.name = 'python' tag.description = 'The Python programming language' tag.save() # Create the author author = User.objects.create_user('testuser', '*****@*****.**', 'password') author.save() # Create the site site = Site() site.name = 'example.com' site.domain = 'example.com' site.save() # Create the post post = Post() post.title = 'My first post' post.text = 'This is [my first blog post](http://127.0.0.1:8000/)' post.slug = 'my-first-post' post.pub_date = timezone.now() post.author = author post.site = site post.save() post.tags.add(tag) post.save() # Check new post saved all_posts = Post.objects.all() self.assertEquals(len(all_posts), 1) only_post = all_posts[0] self.assertEquals(only_post, post) # Get the tag URL tag_url = post.tags.all()[0].get_absolute_url() # Fetch the tag response = self.client.get(tag_url) self.assertEquals(response.status_code, 200) # Check the tag name is in the response self.assertTrue(post.tags.all()[0].name.encode() in response.content) # Check the post text is in the response self.assertTrue( markdown.markdown(post.text).encode() in response.content) # Check the post date is in the response self.assertTrue(str(post.pub_date.year) in response.content) self.assertTrue( _date(post.pub_date, "F").encode('utf-8') in response.content) self.assertTrue(str(post.pub_date.day) in response.content) # Check the link is marked up properly self.assertTrue( '<a href="http://127.0.0.1:8000/">my first blog post</a>' in response.content)
def handle(self, **options): feed = feedparser.parse( 'https://www.headphonezone.in/sitemap_products_1.xml?from=373372541&to=1398753460287' ) for post in Post.objects.all(): post.delete() loop_max = len(feed['entries']) category = Category.objects.get( id="ce867a33-fddf-4e60-89ec-179c9792889d") author = User.objects.get(pk=1) for i in range(0, loop_max): if feed['entries'][i]: blog_post = Post() blog_post.title = feed['entries'][i].title blog_post.slug = slugify(feed['entries'][i].title) link = self.parse_url(feed['entries'][i].link) blog_post.external_url = link blog_post.category = category blog_post.sender = "indiafashionblogger" blog_post.author = author blog_post.short_description = feed['entries'][i].description blog_post.body = self.get_content(link) blog_post.created = datetime.fromtimestamp( mktime(feed['entries'][i].published_parsed)) print(blog_post.short_description) blog_post.save()
def post(self, request, format=None): serializer = PublishSerializer(data=request.data) if not serializer.is_valid(): print(serializer.errors) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) category = serializer.data.get('category') category = Category.objects.get(pk=category) if category is None: return Response(status=status.HTTP_400_BAD_REQUEST) tags = serializer.data.get('tags') with transaction.atomic(): post = Post() post.title = serializer.data.get('title') post.body = serializer.data.get('body') post.category = category post.author = request.user post.save() for tag in tags: tag = Tag.objects.get(pk=tag) post.tags.add(tag) return Response(status=status.HTTP_201_CREATED)
def new_post(blog_id, username, password, post, publish): """ metaWeblog.newPost(blog_id, username, password, post, publish) => post_id """ user = authenticate(username, password) entry = Post() entry.title = post['title'] entry.content = post['description'] entry.excerpt = post['description'][:300] + '...' entry.author = user entry.is_publish = True if post.get( 'post_status') == 'publish' or publish else False if entry.is_publish: entry.publish_content = entry.content entry.publish_excerpt = entry.excerpt if 'categories' in post and post['categories']: # 文章的类别只选择第一项 cat = post['categories'][0] entry.category = Category.objects.get(name=cat) else: entry.category, _ = Category.objects.get_or_create(name='未分类') entry.save() if 'mt_keywords' in post and post['mt_keywords']: ts = [i.strip() for i in post['mt_keywords'].split(',')] for t in ts: tag, _ = Tag.objects.get_or_create(name=t) entry.tags.add(tag) return entry.pk
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)
def test_cascade_deletion_url(self): other_post = Post() other_post.title = "Base 4" other_post.subtitle = "Base Subtitle 4" other_post.text = "Base Text 4" other_post.author = self.user other_post.save() data = { 'author': "Author 18", 'text': "Text 18", } self.client.post("/blog/post/" + str(other_post.pk) + "/comment/", data) data = { 'author': "Author 19", 'text': "Text 19", } self.client.post("/blog/post/" + str(other_post.pk) + "/comment/", data) self.assertEqual(Post.objects.count(), 2) self.assertEqual(Comment.objects.count(), 2) self.assertEqual(other_post.comments.count(), 2) url = "/blog/post/" + str(other_post.pk) + "/remove/" response = self.client.get(url) self.assertEqual(Post.objects.count(), 1) self.assertEqual(Comment.objects.count(), 0)
def editor(request, slug=None): if slug: post = get_object_or_404(Post, slug=slug) else: post = Post() if request.method == 'GET': if request.user.is_authenticated(): return render( request, 'blog/editor.html', {'post': post, 'user': request.user} ) else: return HttpResponseForbidden('Authenticated only') if request.is_ajax(): if request.method == 'POST': data = json.loads(request.body.decode('utf-8')) post.title = data['title'] post.content_raw = data['content'] post.author = request.user post.slug = data['slug'] tags = data['tags'] post.save() for tag in tags: if tag: t, created = Tag.objects.get_or_create(name=tag.strip()) post.tag.add(t) post.save() return HttpResponse( json.dumps( {'slug': post.slug} ) )
def editor(request, slug=None): if slug: post = get_object_or_404(Post, slug=slug) else: post = Post() if request.method == 'GET': if request.user.is_authenticated(): return render(request, 'blog/editor.html', { 'post': post, 'user': request.user }) else: return HttpResponseForbidden('Authenticated only') if request.is_ajax(): if request.method == 'POST': data = json.loads(request.body.decode('utf-8')) post.title = data['title'] post.content_raw = data['content'] post.author = request.user post.slug = data['slug'] tags = data['tags'] post.save() for tag in tags: if tag: t, created = Tag.objects.get_or_create(name=tag.strip()) post.tag.add(t) post.save() return HttpResponse(json.dumps({'slug': post.slug}))
def test_all_post_feed(self): # Create the category category = Category() category.name = 'python' category.description = 'The Python programming language' category.save() # Create the tag tag = Tag() tag.name = 'python' tag.description = 'The Python programming language' tag.save() # Create the author author = User.objects.create_user('testuser', '*****@*****.**', 'password') author.save() # Create the site site = Site() site.name = 'example.com' site.domain = 'example.com' site.save() # Create a post post = Post() post.title = 'My first post' post.text = 'This is my first blog post' post.slug = 'my-first-post' post.pub_date = timezone.now() post.author = author post.site = site post.category = category # Save it post.save() # Add the tag post.tags.add(tag) post.save() # Check we can find it all_posts = Post.objects.all() self.assertEquals(len(all_posts), 1) only_post = all_posts[0] self.assertEquals(only_post, post) # Fetch the feed response = self.client.get('/feeds/posts/') self.assertEquals(response.status_code, 200) # Parse the feed feed = feedparser.parse(response.content) # Check length self.assertEquals(len(feed.entries), 1) # Check post retrieved is the correct one feed_post = feed.entries[0] self.assertEquals(feed_post.title, post.title) self.assertEquals(feed_post.description, post.text)
def post_save(request): if request.method == 'POST': action = request.POST['action'] if request.POST['title'] and request.POST['body'] and request.POST[ 'author']: w_date = timezone.datetime.now() if action == 'add': post = Post() post.create_date = w_date else: post = get_object_or_404(Post, pk=request.POST['blog_id']) post.title = request.POST['title'] post.text = request.POST['body'] post.published_date = w_date post.author = request.user #post.author = request.POST['author'] post.save() return redirect('post_detail', blog_id=str(post.id)) else: post = Post() post.title = request.POST['title'] post.text = request.POST['body'] return render(request, request.POST['error_return'], { 'error': 'All fields are required.', 'post': post }) #return render(request, 'blog/post_new.html',{'error':'All fields are required.'}) else: return render(request, request.POST['error_return'])
def addPost(self, item): #print(item_type, item_title) title = item.find("title").text # Nouveau Blog! link = item.find("link").text # http://mart-e.be/?p=68 ou http://mart-e.be/post/nouveau-blog post_id = item.find("{http://wordpress.org/export/1.2/}post_id").text # 68 pub_date = item.find("pubDate").text # Fri, 05 Feb 2010 11:14:00 +0000 author = item.find("{http://purl.org/dc/elements/1.1/}creator").text # mart content = item.find("{http://purl.org/rss/1.0/modules/content/}encoded").text # the whole article slug = item.find("{http://wordpress.org/export/1.2/}post_name").text # nouveau-blog (CAN BE EMPTY) allow_comments = item.find("{http://wordpress.org/export/1.2/}comment_status").text # open status = item.find("{http://wordpress.org/export/1.2/}status").text # publish publish = item.find("{http://wordpress.org/export/1.2/}post_date").text # 2010-01-05 15:09:00 if slug: posts = Post.objects.filter(slug=slug) else: posts = Post.objects.filter(id=int(post_id)) if len(posts) != 0: print("Skipping {0}".format(posts[0].slug)) return posts[0] try: print("Creating post '"+title+"'") except: print("Creating post #"+post_id) #print("Creating post '{0}'".format(title.decode('utf-8'))) post = Post() post.title = title post.id = post_id if slug: post.slug = slug[:50] else: post.slug = slugify(title)[:50] if author != self.author_name: raise Exception("Unknown author {0}".format(author)) post.author = self.author post.body = content #post.body_html = markdown(parser.inlines(content), output_format="html5") # in wordpress don't use markdown post.body_html = post.body if status == "publish": post.status = 2 else: post.status = 1 if allow_comments == "open": post.allow_comments = True else: post.allow_comments = False post.publish = datetime.strptime(publish,"%Y-%m-%d %H:%M:%S").replace(tzinfo=utc) post.created = post.publish # really, who cares about that post.modifier = post.publish # still don't care post.save() self.addComments(item, post) self.addTags(item, post) return post
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)
def generate_dummy_post(n): for i in range(n): a = Post() a.title = title[randint(0, len(title) - 1)][:80] a.tags = tags[randint(0, len(tags) - 1)].strip().replace(" ", ",") a.content = content a.author = User.objects.get(pk=randint(1, len(User.objects.all()))) a.save()
def setup_comment_test(self): item = Post() item.title = "No Auth Base Post" item.subtitle = "No Auth Base Subtitle" item.text = "No Auth Base Text" item.author = self.user item.save() return item
def test_edit_posts(self): category = Category() category.name = 'python' category.description = 'The python language' category.save() # Create the tag tag = Tag() tag.name = 'python' tag.description = 'The Python programming language' tag.save() author = User.objects.create_user('testuser', '*****@*****.**', 'password') author.save() # site = Site() # site.name = 'nunfuxgvn.com' # site.domain = 'nunfuxgvn.com' # site.save() post = Post() post.title = 'First Post' post.content = 'My first post -yay' post.slug = 'first-post' post.pub_date = timezone.now() post.author = author # post.site = site post.save() post.tags.add(tag) post.save() self.client.login(username='******', password='******') response = self.client.post('/admin/blog/post/1/', { 'title': 'Second Post', 'text': 'This is my second post', 'pub_date_0': '2014-07-17', 'pub_date_1': '11:49:24', 'slug': 'second-post', # 'site': '1', 'category': '1', 'tags': '1' }, follow=True ) self.assertEquals(response.status_code, 200) # Check post successfully changed self.assertTrue('changed successfully' in response.content) # Check post amended all_posts = Post.objects.all() self.assertEquals(len(all_posts), 1) only_post = all_posts[0] self.assertEquals(only_post.title, 'Second Post') self.assertEquals(only_post.content, 'This is my second post')
def create_test_post(): post = Post() post.title = "New post" post.date_posted = "2020-02-08" user = create_test_user() post.author = user post.save() return post, user
def save_model(self, request, obj: Post, form, change): """ Save the model to the database. Automatically attach user from request. """ if not obj.pk: obj.author = request.user super().save_model(request, obj, form, change)
def test_delete_post(self): # Create the category category = Category() category.name = 'python' category.description = 'The Python programming language' category.save() # Create the tag tag = Tag() tag.name = 'python' tag.description = 'The Python programming language' tag.save() # Create the author author = User.objects.create_user('testuser', '*****@*****.**', 'password') author.save() # Create the site site = Site() site.name = 'example.com' site.domain = 'example.com' site.save() # Create the post post = Post() post.title = 'My first post' post.text = 'This is my first blog post' post.slug = 'my-first-post' post.pub_date = timezone.now() post.site = site post.author = author post.category = category post.save() post.tags.add(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/blogengine/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 deleted all_posts = Post.objects.all() self.assertEquals(len(all_posts), 0)
def test_delete_post(self): # Create the category category = Category() category.name = 'python' category.description = 'The Python programming language' category.save() # Create the tag tag = Tag() tag.name = 'python' tag.description = 'The Python programming language' tag.save() # Create the author author = User.objects.create_user('testuser', '*****@*****.**', 'password') author.save() # Create the site site = Site() site.name = 'example.com' site.domain = 'example.com' site.save() # Create the post post = Post() post.title = 'My first post' post.text = 'This is my first blog post' post.slug = 'my-first-post' post.pub_date = timezone.now() post.site = site post.author = author post.save() post.tags.add(tag) post.save() # Check new post saved all_posts = Post.objects.all() self.assertGreater(len(all_posts), 0) # 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 excluído com sucesso self.assertTrue('excluído com sucesso' in response.content) # Check post amended all_posts = Post.objects.all() self.assertEquals(len(all_posts), 0)
def post(self, req, *args, **kwargs): ubody = req.body.decode('utf-8') params = json.loads(ubody) _id = params.get('id') if _id: item = Post.objects.get(id=_id) else: item = Post() item.title = params.get('title') item.body = params.get('body') author_id = params.get('author_id') try: item.author = settings.AUTH_USER_MODEL.objects.get(id=author_id) except: item.author = None item.created = params.get('created') item.updated = params.get('updated') item.save() return JsonResponse({'data': to_json(item)})
def test_tag_page(self): # Create the tag tag = Tag() tag.name = 'python' tag.description = 'The Python programming language' tag.save() # Create the author author = User.objects.create_user('testuser', '*****@*****.**', 'password') author.save() # Create the site site = Site() site.name = 'example.com' site.domain = 'example.com' site.save() # Create the post post = Post() post.title = 'My first post' post.text = 'This is [my first blog post](http://127.0.0.1:8000/)' post.slug = 'my-first-post' post.pub_date = timezone.now() post.author = author post.site = site post.save() post.tags.add(tag) # Check new post saved all_posts = Post.objects.all() self.assertEquals(len(all_posts), 1) only_post = all_posts[0] self.assertEquals(only_post, post) # Get the tag URL tag_url = post.tags.all()[0].get_absolute_url() # Fetch the tag response = self.client.get(tag_url) self.assertEquals(response.status_code, 200) # Check the tag name is in the response self.assertTrue(post.tags.all()[0].name in response.content) # Check the post text is in the response self.assertTrue(markdown.markdown(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) # Check the link is marked up properly self.assertTrue('<a href="http://127.0.0.1:8000/">my first blog post</a>' in response.content)
def post(): if not current_user.is_authenticated: # 如果未登录则重定向到登录页 flash('请先登录!') return redirect(url_for('login')) form = PostForm() if form.validate_on_submit(): post = Post(form.title.data, form.content.data) post.author = current_user db.session.add(post) db.session.commit() return redirect(url_for('index')) return render_template('post.html', pathname='post', form=form)
def test_add_post(): ''' 如何测试数据是否添加成功, 那么首先必须创建数据对象,并增加后,如果不报错,那么数据添加成功. ''' #创建添加7ge对象,数据库中应当有6条 p1 = Post(title="面向对象四大特征", body="面向对象的定义,作用...", summary="面向对象的抽象,继承,封装,多态", author="玄锷无梦", create_time="2018-7-3 7:12:38", modify_time="2018-7-3 7:12:38") p1.save() p2 = Post(title="GIL", summary="GIL全局锁,仅仅存在于Cpython编辑器,和python语言没有关系", body="GIL的存在历史原因,解决办法...", author="玄锷无梦", create_time="2018-6-10 7:22:22", modify_time="2018-7-22 18:18:22") p2.save() p3 = Post.objects.create(title="Linux笔记", summary="这里仅仅收录了常用的linux命令", body="多多使用几次就熟练了...", author="玄锷无梦", create_time="2018-8-8 18:00:00", modify_time="2019-02-03 16:22:00") p4 = Post.objects.create(title="元类", summary="元类就是创建类对象的类", author="玄锷无梦", body="python中一切皆对象....", create_time="2018-8-8 19:22:33", modify_time="2018-12-13 00:00:00") p5 = Post(title="感恩新时代") p5.summary = "进入新时代,应当以历史的角度,看待这一历史巨变" p5.body = "新时代,新历史,新征程..." p5.author = "玄锷无梦" p5.create_time = "2017-12-12 00:00:00" p5.modify_time = "2017-12-12 00:00:00" p6 = Post.objects.get_or_create(title="面向对象四大特征", summary="面向对象的抽象,继承,封装,多态", body="面向对象的思想.....", author="玄锷无梦", create_time="2018-7-3 7:12:38", modify_time="2018-7-3 7:12:38") P7 = Post.objects.get_or_create(title="ORM对象映射数据库", summary="将对象与数据库关联起来,无需直接操作数据库", body="ORM的定义,原因,使用场景.....", author="玄锷无梦", create_tiem="2018-8-8 00:00:00", modify_time="2019-09-09 12:22:33") #计算数据库中的数据数量,判断是否正确 self.assertEqual(Post.objects.all().count(), 6)
def test_basic_post_data(self): post = Post() post.title = u"Some interesting post" post.body = "ABC" * 1000 post.author = "Owner of blog" post.put() response = self.client.get(post.url) self.assertContains(response, post.title) self.assertContains(response, post.body) self.assertContains(response, "Written by Owner of blog")
def test_saving_and_retrieving_posts(self): admin = User.objects.create_superuser('myuser', '*****@*****.**', 'mypassword') initialCount = Post.objects.all().count() first_item = Post() first_item.author = admin first_item.text = 'The first (ever) list item' first_item.save() second_item = Post() second_item.author = admin second_item.text = 'Item the second' second_item.save() current_items = Post.objects.all() self.assertEqual(current_items.count(), initialCount + 2) first_saved_item = current_items[0] second_saved_item = current_items[1] self.assertEqual(first_saved_item.text, 'The first (ever) list item') self.assertEqual(second_saved_item.text, 'Item the second')
def code_create(request): if request.method == 'POST': code = Code() post = Post() try: path = "upload/" file = request.FILES['file'] if not os.path.exists(path): os.makedirs(path) list = GetFileList(path,file.name) version ='1' if len(list)>0: version = str(len(list)+1) file_name = path +request.session['username']+'-'+request.POST['category']+'-'+version+'-'+file.name else: file_name = path +request.session['username']+'-'+request.POST['category']+'-1-'+file.name destination = open(file_name, 'wb+') for chunk in file.chunks(): destination.write(chunk) destination.close() with open(file_name, 'r') as filer: code.wenku = filer.read() code.title = request.POST['title'] code.version = version code.intro = request.POST['body'] code.status = '0' code.path = path+file.name code.size = str(file.size/1000).split('.')[0]+'K' tlist = file.name.split('.') code.type = tlist[len(tlist)-1] code.author = User.objects.get_by_natural_key(request.session['username']) code.category_id = request.POST['category'] code.save() with open(file_name, 'r') as filer: post.body = filer.read() post.title = request.POST['title'] post.author = User.objects.get_by_natural_key(request.session['username']) post.category_id = request.POST['category'] post.save() request.session['codeid'] = code.id return HttpResponseRedirect(reverse('codemg:code_post_list')) except Exception as e: print(e) return HttpResponse(json.dumps({ "status": "fail", }), content_type="application/json") return render(request, "codemg/create.html", { 'username':request.session['username'] })
def test_index(self): category = Category() category.name = 'python' category.description = 'The python language' category.save() # Create the tag tag = Tag() tag.name = 'perl' tag.description = 'The Perl programming language' tag.save() author = User.objects.create_user('testuser', '*****@*****.**', 'password') author.save() # site = Site() # site.name = 'nunfuxgvn.com' # site.domain = 'nunfuxgvn.com' # site.save() post = Post() post.title = 'First Post' post.content = 'My [first post](http://127.0.0.1:8000/) -yay' post.slug = 'first-post' post.pub_date = timezone.now() post.author = author # post.site = site post.category = category post.save() post.tags.add(tag) all_posts = Post.objects.all() self.assertEquals(len(all_posts), 1) # Fetch test_index response = self.client.get('/') self.assertEquals(response.status_code, 200) self.assertTrue(post.title in response.content) self.assertTrue(markdown.markdown(post.content) in response.content) self.assertTrue(post.category.name in response.content) post_tag = all_posts[0].tags.all()[0] self.assertTrue(post_tag.name in response.content) 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) self.assertTrue('<a href="http://127.0.0.1:8000/">first post</a>' in response.content)
def test_saving_and_retrieving_post(self): first_item = Post() first_item.title = "Post 1" first_item.subtitle = "Subtitle 1" first_item.text = "Text 1" first_item.author = self.user first_item.save() second_item = Post() second_item.title = "Post 2" second_item.subtitle = "Subtitle 2" second_item.text = "Text 2" second_item.author = self.user second_item.save() saved_items = Post.objects.all() self.assertEqual(saved_items.count(), 2) first_saved_item = saved_items[0] second_saved_item = saved_items[1] self.assertEqual(first_saved_item.title, 'Post 1') self.assertEqual(second_saved_item.title, 'Post 2')
def test_add_blog(self): author = User(username="******") newblog = Post() newblog.title = "TestBlog" newblog.STATUS = 1 newblog.description = "Test Description" newblog.image = tempfile.NamedTemporaryFile(suffix='.jpg').name newblog.category = "TestCat" newblog.slug = "test-slug" newblog.author = author newblog.content = "Cosas" newblog.updated_on newblog.created_on
def test_get_only_published_posts(self): self.assertEquals(Post.objects.all().count(), 0) for i in range(2): post = Post() post.title = 'sample post title' post.author = self.user post.content = 'sample post content' if i == 0: post.publish() post.save() self.assertEqual(Post.objects.all().count(), 2) self.assertEqual(Post.objects.published().count(), 1)
def setup_visible_test(self): item = Post() item.title = "No Auth Base Post" item.subtitle = "No Auth Base Subtitle" item.text = "No Auth Base Text" item.author = self.user item.save() item2 = Comment() item2.post = item item2.author = "No Auth Base Author" item2.text = "No Auth Base Text" item2.save() return item, item2
def grabPosts(request): d = feedparser.parse('http://tnt-dance.ru/load/rss/') for e in d.entries: post = Post() post.title = e.title post.text = e.summary post.url = e.link post.published_date = timezone.now() post.author = request.user post.save() print ("Title: " + e.title) print ("Link: " + e.link) print ("Content: " + e.summary)
def handle(self, *args, **options): for p in WpPosts.objects.using('old').filter(post_type='post'): post = Post.objects.filter(title=p.post_title).first() if not post: post = Post() post.author = User.objects.get(id=1) post.title = p.post_title post.content = p.post_content post.created_at = p.post_date post.updated_at = p.post_modified post.save() print(p.post_title)
def test_delete_post_unauthenticated(self): item = Post() item.title = "No Auth Post 4" item.subtitle = "No Auth Subtitle 4" item.text = "No Auth Text 4" item.author = self.user item.save() self.assertEqual(Post.objects.count(), 1) new_item = Post.objects.first() url = "/blog/post/" + str(new_item.pk) + "/remove/" response = self.client.get(url) self.assertEqual(Post.objects.count(), 1) self.assertNotEqual(response['location'], "/blog/") self.assertEqual(response['location'], "/accounts/login/?next=" + url)
def test_saving_and_retrieving_items(self): user = User(username='******') user.save() first_item = Post() first_item.author = user first_item.title = 'Test1' first_item.text = 'The first blog item' first_item.save() second_item = Post() second_item.author = user second_item.title = 'Test2' second_item.text = 'Blog item the second' second_item.save() saved_items = Post.objects.all() self.assertEqual(saved_items.count(), 2) first_saved_item = saved_items[0] second_saved_item = saved_items[1] self.assertEqual(first_saved_item.text, 'The first blog item') self.assertEqual(second_saved_item.text, 'Blog item the second')
def test_saving_and_retrieving_comment(self): first_item = Comment() first_item.post = self.post first_item.author = "Author 1" first_item.text = "Text 1" first_item.save() other_post = Post() other_post.title = "Base 2" other_post.subtitle = "Base Subtitle 2" other_post.text = "Base Text 2" other_post.author = self.user other_post.save() second_item = Comment() second_item.post = other_post second_item.author = "Author 2" second_item.text = "Text 2" second_item.save() third_item = Comment() third_item.post = other_post third_item.author = "Author 3" third_item.text = "Text 3" third_item.save() saved_items = Comment.objects.all() self.assertEqual(saved_items.count(), 3) first_saved_item = saved_items[0] second_saved_item = saved_items[1] third_saved_item = saved_items[2] self.assertEqual(first_saved_item.author, 'Author 1') self.assertEqual(second_saved_item.author, 'Author 2') self.assertEqual(third_saved_item.author, 'Author 3') self.assertEqual(first_saved_item.post, self.post) self.assertEqual(second_saved_item.post, other_post) self.assertEqual(third_saved_item.post, other_post) self.assertEqual(self.post.comments.count(), 1) self.assertEqual(other_post.comments.count(), 2) post_comments1 = self.post.comments.all() post_comments2 = other_post.comments.all() self.assertEqual(first_saved_item, post_comments1[0]) self.assertEqual(second_saved_item, post_comments2[0]) self.assertEqual(third_saved_item, post_comments2[1])
def post(self, request, *args, **kwargs): data = request.POST post = Post() post.title = data.get("title").strip() post.content = data.get("content") if post.title and post.content: user = self.request.user # Set post status (see signals) post.author = user post.save() return redirect(post.get_absolute_url()) return redirect("blog:new-post")
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)
def test_edit_post_form_unauthenticated(self): item = Post() item.title = "No Auth Post 2" item.subtitle = "No Auth Subtitle 2" item.text = "No Auth Text 2" item.author = self.user item.save() self.assertEqual(Post.objects.count(), 1) new_item = Post.objects.first() url = "/blog/post/" + str(new_item.pk) + "/edit/" response = self.client.get(url) self.assertEqual(Post.objects.count(), 1) self.assertNotEqual(response['location'], url) self.assertEqual(response['location'], "/accounts/login/?next=" + url) unedited_item = Post.objects.first() self.assertEqual(unedited_item.title, "No Auth Post 2")
def post_create(request): if (request.method == 'POST'): form = PostForm(request.POST) if form.is_valid(): post = Post() post.author = request.user post.category = form.cleaned_data['category'] post.name = form.cleaned_data['name'] post.content = form.cleaned_data['content'] post.status = form.cleaned_data['status'] post.save() return redirect('blog.home') else: form = PostForm() return render(request, 'blog/post_create.html', {'form': form})
def post_create(request): if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): post = Post() post.author = request.user post.category = form.cleaned_data['category'] post.name = form.cleaned_data['name'] post.content = form.cleaned_data['content'] post.status = form.cleaned_data['status'] post.save() return redirect('blog.home') else: form = PostForm() return render(request, 'blog/post_create.html', {'form': form})
def blog_post(request): user = request.user if request.method == 'POST': details=Post() details.title=request.POST['title'] details.author=user#foreign key posting details.photo=request.FILES['photo'] details.content=request.POST['content'] details.public=request.POST['checks']#checkbox posting details.created=request.POST['created'] details.updated=request.POST['updated'] details.published=request.POST['published'] details.save() return HttpResponseRedirect('/post_list/') else: return render(request,'blog/blog_post.html',{'user':user})
def test_edit_post(self): # Create author author = User.objects.create_user('testuser', '*****@*****.**', 'password') author.save() # Create site site = Site() site.name = 'example.com' site.domain = 'example.com' site.save() # Create the post post = Post() post.title = 'My first post' post.text = 'This is my first blog post' post.pub_date = timezone.now() post.author = author post.site = site post.save() # Log in self.client.login(username='******', password="******") # Edit the post post_id = str(post.id) response = self.client.post('/admin/blog/post/' + post_id +'/', { 'title': 'My second post', 'slug': 'my-second-post', 'text': 'This is my second blog post', 'pub_date_0': '2013-12-28', 'pub_date_1': '22:00:04', 'site': '1' }, follow=True ) self.assertEquals(response.status_code, 200) # Check changed successfully self.assertTrue('changed successfully' in response.content) # Check post amended all_posts = Post.objects.all() self.assertEquals(len(all_posts), 1) only_post = all_posts[0] self.assertEquals(only_post.title, 'My second post') self.assertEquals(only_post.text, 'This is my second blog post')
def test_create_post(self): # Create author author = User.objects.create_user('testuser', '*****@*****.**', 'password') author.save() # Create site site = Site() site.name = 'example.com' site.domain = 'example.com' site.save() # Create the post post = Post() # Set the attributes post.title = 'My first post' post.text = 'This is my first blog post' post.slug = slugify(post.title) post.pub_date = timezone.now() post.author = author post.site = site # Save it post.save() # Check we can find it all_posts = Post.objects.all() self.assertEquals(len(all_posts), 1) only_post = all_posts[0] self.assertEquals(only_post, post) # Check attributes self.assertEquals(only_post.title, 'My first post') self.assertEquals(only_post.text, 'This is my first blog post') self.assertEquals(only_post.slug, 'my-first-post') self.assertEquals(only_post.site.name, 'example.com') self.assertEquals(only_post.site.domain, 'example.com') self.assertEquals(only_post.pub_date.day, post.pub_date.day) self.assertEquals(only_post.pub_date.month, post.pub_date.month) self.assertEquals(only_post.pub_date.year, post.pub_date.year) self.assertEquals(only_post.pub_date.hour, post.pub_date.hour) self.assertEquals(only_post.pub_date.minute, post.pub_date.minute) self.assertEquals(only_post.pub_date.second, post.pub_date.second) self.assertEquals(only_post.author.username, 'testuser') self.assertEquals(only_post.author.email, '*****@*****.**')
def test_delete_post(self): category = Category() category.name = 'python' category.description = 'The python language' category.save() # Create the tag tag = Tag() tag.name = 'python' tag.description = 'The Python programming language' tag.save() author = User.objects.create_user('testuser', '*****@*****.**', 'password') author.save() # site = Site() # site.name = 'nunfuxgvn.com' # site.domain = 'nunfuxgvn.com' # site.save() post = Post() post.title = 'First Post' post.test = 'My first post' post.slug = 'first-post' post.pub_date = timezone.now() post.author = author # post.site = site post.save() post.tags.add(tag) post.save() all_posts = Post.objects.all() self.assertEquals(len(all_posts), 1) self.client.login(username='******', password='******') response = self.client.post('/admin/blog/post/1/delete/', { 'post': 'yes' }, follow=True) self.assertEquals(response.status_code, 200) self.assertTrue('deleted successfully' in response.content) all_posts = Post.objects.all() self.assertEquals(len(all_posts), 0)
def test_delete_post(self): # Create author author = User.objects.create_user('testuser', '*****@*****.**', 'password') author.save() # Create site site = Site() site.name = 'example.com' site.domain = 'example.com' site.save() # Create the post post = Post() post.title = 'My first post' post.text = 'This is my first blog post' post.slug = 'my-first-post' post.pub_date = timezone.now() post.author = author post.site = site post.save() # Check new post saved all_posts = Post.objects.all() self.assertEquals(len(all_posts), 1) # Log in self.client.login(username='******', password="******") post_id = str(post.id) # Delete the post response = self.client.post('/admin/blog/post/' + post_id +'/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)
def test_index(self): # Create author author = User.objects.create_user('testuser', '*****@*****.**', 'password') author.save() # Create site site = Site() site.name = 'example.com' site.domain = 'example.com' site.save() # Create the post post = Post() post.title = 'My first post' post.text = 'This is [my first blog post](http://127.0.0.1:8000/)' post.slug = 'my-first-post' post.pub_date = timezone.now() post.author = author post.site = site post.save() # Check new post saved all_posts = Post.objects.all() self.assertEquals(len(all_posts), 1) # Fetch the index response = self.client.get('/blog') self.assertEquals(response.status_code, 200) # Check the post title is in the response self.assertTrue(post.title in response.content) # Check the post text is in the response self.assertTrue(markdown.markdown(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) self.assertTrue('<a href="http://127.0.0.1:8000/">my first blog post</a>' in response.content)
def create_post(data): draft_id = data.get('id') try: post = Post.objects.get(draft_id=draft_id) except Post.DoesNotExist: post = Post(draft_id=draft_id) title = data.get('name') body = data.get('content') author = User.objects.get(username='******') post.title = title post.slug = slugify(title.decode()) post.body = body post.tease = body[:200] + '...' post.author = author post.save() return post
def new(request): print("---- new ----") print("request.GET = {}".format(request.GET)) print("request.POST = {}".format(request.POST)) print("request.FILES = {}".format(request.FILES)) if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): title = form.cleaned_data['title'] content = form.cleaned_data['content'] post = Post(title=title, content=content) post.author = request.user post.save() messages.info(request, "새 글이 등록되었습니다.") return redirect('blog.views.index') else: form = PostForm() return render(request, "blog/form.html", { 'form': form, })
def test_create_post(self): # Create the category category = Category() category.name = 'python' category.description = 'The Python programming language' category.save() # Create the tag tag = Tag() tag.name = 'python' tag.description = 'The Python programming language' tag.save() # Create the author author = User.objects.create_user('testuser', '*****@*****.**', 'password') author.save() # Create the site site = Site() site.name = 'example.com' site.domain = 'example.com' site.save() # Create the post post = Post() # Set the attributes post.title = 'My first post' post.text = 'This is my first blog post' post.slug = 'my-first-post' post.pub_date = timezone.now() post.author = author post.site = site post.category = category # Save it post.save() # Add the tag post.tags.add(tag) post.save() # Check we can find it all_posts = Post.objects.all() self.assertEquals(len(all_posts), 1) only_post = all_posts[0] self.assertEquals(only_post, post) # Check attributes self.assertEquals(only_post.title, 'My first post') self.assertEquals(only_post.text, 'This is my first blog post') self.assertEquals(only_post.slug, 'my-first-post') self.assertEquals(only_post.site.name, 'example.com') self.assertEquals(only_post.site.domain, 'example.com') self.assertEquals(only_post.pub_date.day, post.pub_date.day) self.assertEquals(only_post.pub_date.month, post.pub_date.month) self.assertEquals(only_post.pub_date.year, post.pub_date.year) self.assertEquals(only_post.pub_date.hour, post.pub_date.hour) self.assertEquals(only_post.pub_date.minute, post.pub_date.minute) self.assertEquals(only_post.pub_date.second, post.pub_date.second) self.assertEquals(only_post.author.username, 'testuser') self.assertEquals(only_post.author.email, '*****@*****.**') self.assertEquals(only_post.category.name, 'python') self.assertEquals(only_post.category.description, 'The Python programming language') # Check tags post_tags = only_post.tags.all() self.assertEquals(len(post_tags), 1) only_post_tag = post_tags[0] self.assertEquals(only_post_tag, tag) self.assertEquals(only_post_tag.name, 'python') self.assertEquals(only_post_tag.description, 'The Python programming language')
def parse_xml(): et = ET.ElementTree(file='/home/jasper/Downloads/jasper.xml') root = et.getroot() user = User.objects.get(username='******') count = 1 alias_re = re.compile(r'^[a-z|0-9|\-]+$') for channel in root.findall('channel'): for item in channel.findall('item'): title = item.find('title') post_name = item.find('{http://wordpress.org/export/1.2/}post_name') pubDate = item.find('pubDate') description = item.find('description') content = item.find('{http://purl.org/rss/1.0/modules/content/}encoded') categories = item.findall('category') tags = [] category = Category() for ca in categories: if ca.attrib['domain'] == 'post_tag': tags.append(ca.text) else: try: category = Category.objects.get(name=ca.text) except Category.DoesNotExist: category.name = ca.text if alias_re.match(ca.attrib['nicename']): category.alias = ca.attrib['nicename'] else: category.alias = category.name print category.alias category.save() try: Post.objects.get(title=title.text) print title.text, 'already exist' continue except Post.DoesNotExist: pass post = Post() post.title = title.text post.category = category if alias_re.match(post_name.text): post.alias = post_name.text else: post.alias = title.text print post.alias post.content = content.text post.content_html = content.text if not description.text: post.summary = content.text[:140] else: post.summary = description.text post.is_old = True post.tags = ','.join(tags) create_time = pubDate.text[:-6] tf = '%a, %d %b %Y %H:%M:%S' post.old_pub_time = datetime.strptime(create_time, tf) print post.old_pub_time post.author = user try: post.save() print count, post count += 1 except Exception, e: print e
def test_edit_post(self): # Create the category category = Category() category.name = 'python' category.description = 'The Python programming language' category.save() # Create the tag tag = Tag() tag.name = 'python' tag.description = 'The Python programming language' tag.save() # Create the author author = User.objects.create_user('testuser', '*****@*****.**', 'password') author.save() # Create the site site = Site() site.name = 'example.com' site.domain = 'example.com' site.save() # Create the post post = Post() post.title = 'My first post' post.text = 'This is my first blog post' post.slug = 'my-first-post' post.pub_date = timezone.now() post.author = author post.site = site post.save() post.tags.add(tag) post.save() # Log in self.client.login(username='******', password="******") # Edit the post response = self.client.post('/admin/blogengine/post/1/', { 'title': 'My second post', 'text': 'This is my second blog post', 'pub_date_0': '2013-12-28', 'pub_date_1': '22:00:04', 'slug': 'my-second-post', 'site': '1', 'category': '1', 'tags': '1' }, follow=True ) self.assertEquals(response.status_code, 200) # Check changed successfully self.assertTrue('changed successfully' in response.content) # Check post amended all_posts = Post.objects.all() self.assertEquals(len(all_posts), 1) only_post = all_posts[0] self.assertEquals(only_post.title, 'My second post') self.assertEquals(only_post.text, 'This is my second blog post')