def handle(self, *args, **options): user = \ get_user_model().objects.get_or_create(email='*****@*****.**', username='******', password='******')[0] pcategory = Category.objects.get_or_create(name='我是父类目', parent_category=None)[0] category = Category.objects.get_or_create(name='子类目', parent_category=pcategory)[0] category.save() basetag = Tag() basetag.name = "标签" basetag.save() for i in range(1, 20): article = Article.objects.get_or_create( category=category, title='nice title ' + str(i), body='nice content ' + str(i), author=user)[0] tag = Tag() tag.name = "标签" + str(i) tag.save() article.tags.add(tag) article.tags.add(basetag) article.save() from DjangoBlog.utils import cache cache.clear() self.stdout.write(self.style.SUCCESS('created test datas \n'))
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 setUp(self): self.app = create_app('test') self.app_context = self.app.app_context() self.app_context.push() db.create_all() self.client = self.app.test_client() tag = Tag() tag.name = 'tagx' db.session.add(tag) category = Category() category.name = 'categoryx' db.session.add(category) db.session.commit() article = Article() article.title = 'articlex' article.slug = 'slugx' article.category = category article.content = 'contentx' article.tags = [tag] db.session.add(category) db.session.commit() user = User() user.name = 'admin' user.password = '******' db.session.add(user) db.session.commit()
def test_edit_tag(self): # Create the tag tag = Tag() tag.name = 'python' tag.description = 'The Python programming language' tag.save() # Log in self.client.login(username='******', password="******") # Edit the tag response = self.client.post( '/admin/blog/tag/1/', { 'name': 'perl', 'description': 'The Perl programming language' }, follow=True) self.assertEquals(response.status_code, 200) # Check modificado com sucesso self.assertTrue('modificado com sucesso' in response.content) # Check tag amended all_tags = Tag.objects.all() self.assertEquals(len(all_tags), 1) only_tag = all_tags[0] self.assertEquals(only_tag.name, 'perl') self.assertEquals(only_tag.description, 'The Perl programming language')
def post(request): now=time.localtime() article =Article() if request.POST.has_key('content'): article.author = cgi.escape(request.POST['author'].decode('utf-8')) article.content = request.POST['content'].decode('utf-8') article.tags = request.POST['tags'].decode('utf-8') article.title = cgi.escape(request.POST['title'].decode('utf-8')) now_date = datetime.datetime.now()+timedelta(hours=+8) s = now_date.ctime() article.date = str(now_date)[:-7] article.gmtdate = "%s, %s %s %s %s GMT" % (s[:3] ,s[8:10], s[4:7] ,s[-4:] ,s[11:19]) article.year = str(datetime.datetime.now()+timedelta(hours=+8))[:4] article.month = str(datetime.datetime.now()+timedelta(hours=+8))[5:7] if not article.title: if len(article.content) > 11: article.title = article.content[:12] + '...' else: article.title=article.content article.id=time.strftime('%Y%m%d%H%M%S',now) if article.content: article.put() for tag_name in filter(None,article.tags.split(' ')): tag = Tag() tag.tag = tag_name tag.article_id = article.id tag.put() return HttpResponseRedirect("/blog/")
def form_valid(self, form): context = self.get_context_data() formset = context['formset'] if formset.is_valid(): tags = self.request.POST.get("tag") tag_list = re.split("[,、]", tags) blog = form.save(commit=False) blog.save() for tag in tag_list: tag = tag.strip() if tag != "": exists_tag = Tag.objects.get_or_none(name=tag) if exists_tag: blog.tag.add(exists_tag) else: tag_obj = Tag(name=tag) tag_obj.save() blog.tag.add(tag_obj) messages.success(self.request, "保存しました。") return super().form_valid(form) else: context['form'] = form messages.error(self.request, "保存に失敗しました。") return self.render_to_response(context)
def post(self): post_parser = reqparse.RequestParser() post_parser.add_argument('name', type=str, required=True, help='the argument cannot be blank') post_parser.add_argument('article_ids', type=int, action='append', help='the argument cannot be blank') args = post_parser.parse_args() try: tag = Tag() tag.name = args['name'] tag.articles = [ Article.query.get_or_404(id) for id in args['article_ids'] ] if args['article_ids'] else [] db.session.add(tag) db.session.commit() except sqlalchemy.exc.IntegrityError: db.session.rollback() return {'status': 400, 'msg': '字段冲突'}, 400 except sqlalchemy.exc.InvalidRequestError: db.session.rollback() return {'status': 400, 'msg': '字段冲突'}, 400 return {'status': 200, 'msg': '新建标签成功'}
def test_article_get(self): r = self.client.get(self.url + '/article') self.assertEqual(r.status_code, 401) article = Article() article.title = 'title-test' article.slug = 'test' article.content = 'content ' * 20 db.session.add(article) db.session.commit() r = self.client.get(self.url + '/article?slug=test') self.assertEqual(r.status_code, 401) tag = Tag() tag.name = 'tag' db.session.add(tag) category = Category() category.name = 'category' db.session.add(category) db.session.commit() article = Article() article.title = 'article' article.slug = 'slug' article.category = category article.content = 'content' article.tags = [tag] db.session.add(category) db.session.commit() r = self.client.get(self.url + '/article?slug=slug') self.assertEqual(r.status_code, 401)
def handle(self, **options): if not User.objects.exists(): usernames = words(NUMBER_OF_USERS).split(" ") User.objects.bulk_create([ User(username=username, password=username, email="*****@*****.**" % username) for username in usernames ]) if not Tag.objects.exists(): Tag.objects.bulk_create([Tag(name=word) for word in WORDS]) if not Post.objects.exists(): users = list(User.objects.all()) tags = list(Tag.objects.all()) for p in range(NUMBER_OF_POSTS): post = Post.objects.create( author=choice(users), title=sentence(), body="\n".join(paragraphs(randint(3, 5))), thumbnail="http://test.com/test.jpg", is_published=choice([True, True, False]), ) post.tags.add(*sample(tags, randint(0, 10))) post.liked_by.add(*sample(users, randint(0, 10))) for i in range(comment_count()): Comment.objects.create( user=choice(users), body=paragraph(), post=post, parent=None if random() < 0.5 or not post.is_published else choice(post.comment_set.all() or [None]))
def form_valid(self, form): tags = self.request.POST.get("tag") tag_list = re.split("[,、]", tags) blog = form.save(commit=False) blog.save() if not tags: messages.success(self.request, "更新しました。") return super().form_valid(form) blog.tag.clear() for tag in tag_list: tag = tag.strip() if tag != "": exists_tag = Tag.objects.get_or_none(name=tag) if exists_tag: blog.tag.add(exists_tag) else: tag_obj = Tag(name=tag) tag_obj.save() blog.tag.add(tag_obj) messages.success(self.request, "更新しました。") return super().form_valid(form)
def create_blog(request): if request.method == 'POST': form = BlogForm(request.POST) if form.is_valid(): cd = form.cleaned_data blog = Blog.objects.create(author=request.user, title=cd['title'], body=cd['body'], column=cd['column']) tags = request.POST.getlist('tags[]', []) tag_list = [] for tag in tags: tag_obj = Tag(name=tag, blog=blog) tag_list.append(tag_obj) Tag.objects.bulk_create(tag_list) return JsonResponse({ "code": 200, 'msg': 'Created', 'url': reverse('blog:blog_detail', kwargs={"slug": blog.slug}) }) else: return JsonResponse({ "code": 400, 'msg': 'Invalid request' + str(form.errors) }) else: columns = Column.objects.all() return render(request, 'myadmin/blog/blog.html', {"columns": columns})
def handle(self, *args, **options): amount_post = options["amount_post"] clean = options["clean"] if clean: Post.objects.all().delete() Tag.objects.all().delete() fake = faker.Faker() fake.add_provider(MarkdownPostProvider) tags = [] for i in range(5): tags.append(Tag(name=fake.color_name())) tags = Tag.objects.bulk_create(tags) for p in range(amount_post): post = Post.objects.create( title=fake.sentence(), slug=fake.slug(), meta_description=fake.paragraph(nb_sentences=1), content=fake.post(size="medium"), date=fake.date_object(), published=True, ) post.tags.set(random.choices(tags))
def test_blog_post_model(): user = CustomUser(email="*****@*****.**", username="******") user.save() tag1 = Tag(name="tag1") tag1.save() tag2 = Tag(name="tag2") tag2.save() post = BlogPost(author=user, title="Test title!", body="post body") post.tags.set([tag1, tag2]) post.save() assert post.author.username == "test" assert post.title == "Test title!" assert post.slug == "test-title" assert post.tags.all()[1] == tag2 assert post.body == "post body" assert str(post) == post.title
def post(self): post_args = self.post_parser.parse_args() channel_name = post_args.get('channel') channel = Channel.query.filter_by(name=channel_name).first() now = datetime.utcnow() tags = post_args.get('tags') or [] if not channel: return jsonify( message='Please choose a channel for publishing.'), 404 try: post = Post() post.name = post_args.get('name') post.channel = channel.name post.content = post_args.get('content') post.publish_time = now post.save() for tag in tags: t = Tag.query.filter_by(name=tag).first() or Tag() t.post_id = post.id t.name = tag t.save() except IntegrityError: db.session.rollback() return jsonify(message='Post {} already exists.'.format( post_args.get('name'))), 409 return jsonify(marshal(post, self.post_fields)), 201
def get_tag(tag, create=True): try: ret = Tag.objects.get(tag=tag) except: if not create: return None ret = Tag(tag=tag, nr_refs=0) return ret
def create_author(author_details): new_author = Tag(author_name=author_details["author_name"], author_username=author_details["author_username"], author_facebook=author_details["author_facebook"], author_website=author_details["author_webiste"]) new_author.save()
def fake_tag(count=20): for i in range(count): tag = Tag(name=fake.word()) db.session.add(tag) try: db.session.commit() except IntegrityError: db.session.rollback()
def post(self, request): try: name = request.POST.get('name') description = request.POST.get('description') tag = Tag(name=name, description=description) tag.save() except Exception, e: return JsonResponse({'msg': '新增失败\n%s' % unicode(e)}, status=500)
def _save_tags(post, tags_field): post.tags.clear() for tag_item in tags_field.split(','): tag = Tag.query.filter_by(name=slugify(tag_item)).first() if not tag: tag = Tag(name=slugify(tag_item)) db.session.add(tag) post.tags.append(tag) return post
def fake_tags(count=20): for i in range(count): tag = Tag( name=fake.word(), timestamp=fake.date_time_this_year(), post=Post.query.get(random.randint(1, Post.query.count())) ) db.session.add(tag) db.session.commit()
def check_or_create_tag(name): try: x = Tag.objects.get(slug=name) except Tag.DoesNotExist: x = Tag(name) x.slug = name.strip() x.save() print x return x
def test_is_count_one(self): category = Category(name="テストカテゴリー") category.save() tag = Tag(name="テストタグ") tag.save() post = Post(category=category, title="test_title", body="test_body") post.save() saved_posts = Post.objects.all() self.assertEqual(saved_posts.count(), 1)
def get_tag_from_string(cls, tag_string): raw_tags = tag_string.split(',') tag = [tag.strip() for tag in raw_tags if tag.strip()] # filter the empty string existing_tag = Tag.query.filter( Tag.name.in_(tag)) # Query the database for the tags we have new_names = set(tag) - set([tag.name for tag in existing_tag]) new_tags = [Tag(name=name) for name in new_names ] # Create new tags for those are not in database return list(existing_tag) + new_tags
def test_tag_get(self): r = self.client.get(self.url + '/tag?name=a') self.assertEqual(r.status_code, 404) tag = Tag() tag.name = 'a' db.session.add(tag) db.session.commit() r = self.client.get(self.url + '/tag?name=a') self.assertEqual(r.status_code, 200) self.assertTrue('a' in r.get_data(as_text=True))
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 setUp(self): db.drop_all() db.create_all() tag1 = Tag(value="tag1") db.session.add(tag1) tag2 = Tag(value="tag2") db.session.add(tag2) user = User(user_name="user1", first_name="First Name", last_name="Last Name", password=generate_password_hash("1234")) db.session.add(user) post = Post( title="Post title", summary="""Post summary""", body="""Post body""", author=user, created=datetime(2020, 1, 15, 10, 30), updated=datetime(2020, 1, 15, 10, 30), ) post_with_tags = Post(title="Second post title", summary="""Second post summary""", body="""Second post body""", author=user, created=datetime(2020, 1, 15, 10, 30), updated=datetime(2020, 1, 15, 10, 30), tags=[tag1, tag2]) db.session.add(post) db.session.add(post_with_tags) db.session.commit() chrome_options = webdriver.ChromeOptions() chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("--disable-dev-shm-usage") self.driver = webdriver.Chrome(options=chrome_options) self.driver.get(self.get_server_url())
def create_tag(tag_name): if Tag.query.filter_by(name=tag_name).first() is not None: flash('You have same Tag.', category='danger') return try: new_tag = Tag(name=tag_name) db.session.add(new_tag) db.session.commit() flash('You have successfully add the tag.', category='success') except exc.IntegrityError: db.session.rollback()
def blog_input_request(request): # form submit if request.method == 'POST' and request.user.is_authenticated: try: # title title = request.POST['title'] #content contentOrder = request.POST.get("contentOrder") contentItems = json.dumps(request.POST.getlist("myContent[]")) # author author = request.user.author assert contentOrder != None and contentOrder != "" # blog shouldn't be empty assert author != None # valid user must exist # saving images files = request.FILES.getlist("myfile[]") blog = Blog(title=title, body=contentItems, contentOrder=contentOrder, author=author, no_of_images=len(files)) blog.save() #tags existingTags = json.loads(request.POST["existingTags"]) newTags = json.loads(request.POST["newTags"]) for tagId in existingTags: tag = Tag.objects.get(pk=tagId) blog.tags.add(tag) blog.save() for tagName in newTags: tag = Tag(name=tagName) tag.save() blog.tags.add(tag) blog.save() for i in range(len(files)): destination_name = 'blog/static/blog/upload/' + str( blog.id) + '_' + str(i) + '_' + files[i].name with open(destination_name, 'wb+') as destination: for chunk in files[i].chunks(): destination.write(chunk) return HttpResponseRedirect( reverse("author_posts", kwargs={'author_id': author.id})) except AssertionError: print(f"Error adding new blog") return HttpResponseRedirect(reverse("index")) else: return HttpResponse('Access Denied')
def add_new_tag(request): if request.method == 'POST': text = request.POST.get('text') slug = request.POST.get('slug') tag = Tag() tag.text = text tag.slug = slug tag.save() my_dict = {'taxonomy':'tag'} return render(request, 'backend/taxonomy.html', context=my_dict)
def test_not_insert_same_name(self): ''' 同一のnameを持つオブジェクトは追加できない。 ''' try: for i in range(2): tag = Tag() tag.name = 'Python' tag.save() except Exception as e: self.assertEquals(str(e.__cause__), 'UNIQUE constraint failed: blog_tag.name')