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 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 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 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 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 blog_entry_add_view(request): """ lets superusers add a blog entry :param request: :return: """ options = blogAttributes() entryForm = EntryForm() options['form'] = entryForm options['tags'] = Tag.objects.all() if request.POST and request.method == 'POST': entryForm = EntryForm(request.POST) if entryForm.is_unique(request): entry = entryForm.customSave(request.user) # loop through the tags if len(entry.tags) > 0: tags = entry.tags.split(',') for tag in tags: # if the tag doesn't exist if not Tag.objects.filter(name=tag).exists(): # save the tag t = Tag() t.name = tag t.save() messages.add_message(request, messages.SUCCESS, 'The Entry has been saved') return redirect(blog_view) else: messages.add_message(request, messages.ERROR, 'An Entry with this Title already exists') return render_to_response('entryForm.html', options, context_instance=RequestContext(request))
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 post_new(request): """新建文章""" if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.author = request.user # 开始处理标签 print post.author ptags = request.POST['tags'].strip() all_tags = [] if ptags: tags = ptags.split(',') for tag in tags: try: t = Tag.objects.get(name=tag) except Tag.DoesNotExist: t = Tag(name=tag) t.save() all_tags.append(t) post.save() for tg in all_tags: post.tags.add(tg) return redirect('blog.views.post_detail', pk=post.pk) else: form = PostForm() return render_to_response('post_edit.html', {'form': form, 'is_new': True},context_instance=RequestContext(request))
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 blog_entry_edit_view(request, eID): """ lets superusers edit a blog entry :param request: :return: """ options = blogAttributes() entry = get_object_or_404(Entry, id=eID) options['entry'] = entry options['form'] = EntryForm(instance=entry) if request.POST and request.method == 'POST': entryForm = EntryForm(request.POST, instance=get_object_or_404(Entry, id=eID)) if entryForm.is_unique(request, entry): if entryForm.has_changed(): entry = entryForm.customSave(request.user) # loop through the tags if len(entry.tags) > 0: tags = entry.tags.split(',') for tag in tags: # if the tag doesn't exist if not Tag.objects.filter(name=tag).exists(): # save the tag t = Tag() t.name = tag t.save() messages.add_message(request, messages.SUCCESS, 'The Entry has been updated') return redirect(blog_entry_view, titleSlug=entry.title_slug) else: messages.add_message(request, messages.INFO, 'No changes have been made') else: messages.add_message(request, messages.ERROR, 'An Entry with this Title already exists') return render_to_response('entryForm.html', options, context_instance=RequestContext(request))
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/blogengine/tag/1/', { 'name': 'perl', 'description': 'The Perl programming language' }, follow=True) self.assertEquals(response.status_code, 200) # Check changed successfully self.assertTrue('changed successfully' 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 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 admin_edit_post(request, post_id): if users.is_current_user_admin(): post = Post.get_by_id(int(post_id)) if not post: raise Http404 if request.method == 'GET': tp = Tag_Post.all().filter('post', post) tags = '' # Get all tags for tag in tp: tags += tag.tag.title + ',' form = PostForm({'title':post.title, 'category':post.category.key(), 'content':post.content, 'tags':tags}) elif request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): # delete related tag_post for tp in post.tags: tp.delete() p = form.save(commit=False) post.author = users.get_current_user() post.category = p.category post.content = p.content post.put() # add tag_post tagText = request.POST['tags'] if tagText: tags = tagText.split(',') for tag in tags: if tag: tag = string.lower(string.strip(tag)) t = Tag.all().filter("title = ", unicode(tag, "utf-8")).get() if not t: t = Tag(title=unicode(tag, "utf-8")) t.put() Tag_Post(tag=t, post=post).put() return HttpResponseRedirect('/admin') return render_to_response('admin/edit.html', dictionary={ 'form':form, 'type': 'Edit Post', }, context_instance=RequestContext(request) ) else: return HttpResponseRedirect('/')
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 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 test_get_tag_with_name(self): tag1 = Tag.get_tag_with_name(name='Tag_1') tag2 = Tag.get_tag_with_name(name='Tag_2') tag3 = Tag.get_tag_with_name(name='Tag3') tag4 = Tag.get_tag_with_name(name='Tag_4') self.assertEqual(tag1.name, 'Tag 1') self.assertEqual(tag2.name, 'Tag_2') self.assertEqual(tag3.name, 'Tag3') self.assertEqual(tag4.name, 'Tag#4')
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 addtag(request): tag_name=request.GET.get('tag_name') newtag=Tag() newtag.tag_name=tag_name newtag.save() id=newtag.id tag={'id':id,'tag_name':tag_name} tag=json.dumps(tag) return HttpResponse(tag)
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 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 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.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_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 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 tag_add(request): if request.method == 'POST': form = TagaddForm(request.POST) if form.is_valid(): cd = form.cleaned_data name = cd['tag_name'] tag = Tag(tag_name = name) tag.save() return HttpResponseRedirect("/blog/admin/tag_list/") else: form = TagaddForm() return render_to_response('admin_tagadd.html',locals(), context_instance=RequestContext(request))
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')
def action_update_tags(self,slug=None): for tag in Tag.all(): tag.delete() for entry in Entry.all().filter('entrytype =','post'): if entry.tags: for t in entry.tags: try: Tag.add(t) except: traceback.print_exc() self.write(_('"All tags for entry have been updated."'))
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 get_tags(tags): """ Get tags from request info. """ assert isinstance(tags, basestring) # comma separator tags = tags.split(',') for tag in tags: tag = tag.strip() Tag.get_or_insert(tag, tag=tag) return tags
def savepost(request): c = Category(name='category test') c.save() t = Tag(name='tag1') t.save() user = User.objects.get(username='******') p = Post(title='title test', body='body test', created_time=timezone.now(), modified_time=timezone.now(), category=c, author=user) p.save() return HttpResponse('<P>添加数据成功</P>')
def addTag(request): if (request.method == 'POST'): form = TagForm(request.POST) if (form.is_valid()): Tag = form.save(commit=False) Tag.save() return HttpResponseRedirect('/blog/newPost') else: raise ValidationError(_('Invalid value'), code='invalid') else: form = TagForm() return render(request, 'blogviews/newTag.html', {'form': form})
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_saving_retrieving_post(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() actual_post = saved_posts[ 0] #0は、saved_postsというリストから最初の値を取り出すという意味。2番目の値を取り出すなら1 self.assertEqual(actual_post.title, "test_title") self.assertEqual(actual_post.body, "test_body")
def test_delete_url(self): category = Category(name="テストカテゴリー") category.save() tag = Tag(name="テストタグ") tag.save() post = Post(category=category, title="test_title", body="test_body") post.save() url = reverse("blog:delete", kwargs={"pk": post.pk}) response = self.client.get(url) self.assertEqual(response.status_code, 200) template = "blog/post_comfirm_delete.html" self.assertTemplateUsed(template)
def handle(self, *args, **options): import markdown md = markdown.Markdown(extensions=['meta']) path = options['dir'] if 'dir' in options else None User = get_user_model() author = User.objects.first() if path and os.path.exists(path): filenames = os.listdir(path) for filename in filenames: if filename.endswith('md'): print(filename) full_path = os.path.join(path, filename) file = open(full_path, encoding='utf-8').read() md.convert(file) metas = md.Meta body = file if 'categories' in metas and metas['categories'][0]: category_name = metas['categories'][0] else: category_name = '无分类' category = Category.objects.filter( name=category_name).first() if not category: category = Category(name=category_name) category.save() article = Article(title=metas['title'][0], author=author, body=body, category=category) if 'slug' in metas and metas['slug'][0]: article.slug = metas['slug'][0] if 'date' in metas and metas['date'][0]: article.pub_time = metas['date'][0] else: article.pub_time = datetime.datetime.now() if 'updated' in metas and metas['updated'][0]: article.modify_time = metas['updated'][0] else: article.modify_time = article.pub_time article.save() if 'tags' in metas and metas['tags']: for tag_name in metas['tags']: if tag_name: tag = Tag.objects.filter(name=tag_name).first() if not tag: tag = Tag(name=tag_name) tag.save() article.tags.add(tag) article.save()
def GET(self,tags=None): urls = [] def addurl(loc,lastmod=None,changefreq=None,priority=None): url_info = { 'location': loc, 'lastmod': lastmod, 'changefreq': changefreq, 'priority': priority } urls.append(url_info) addurl(self.blog.baseurl,changefreq='daily',priority=0.9 ) entries = Entry.all().filter(published = True).order_by('-date')[0:self.blog.sitemap_entries]#.fetch(self.blog.sitemap_entries) for item in entries: loc = "%s/%s" % (self.blog.baseurl, item.link) addurl(loc,item.mod_date or item.date,'never',0.6) if self.blog.sitemap_include_category: cats=Category.all() for cat in cats: loc="%s/category/%s"%(self.blog.baseurl,cat.slug) addurl(loc,None,'weekly',0.5) if self.blog.sitemap_include_tag: tags=Tag.all() for tag in tags: loc="%s/tag/%s"%(self.blog.baseurl, urlencode(tag.tag)) addurl(loc,None,'weekly',0.5) ## self.response.headers['Content-Type'] = 'application/atom+xml' self.render('/admin/views/sitemap.xml', {'urlset':urls}, content_type='text/xml')#, content_type='application/xhtml+xml')
def content_html(self): from blog.models import Post, Tag 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()} return render_to_string('config/blocks/sidebar_posts.html', context) elif self.display_type == self.DISPLAY_HOT: context = {'posts': Post.hot_posts()} return 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) } return render_to_string('config/blocks/sidebar_comments.html', context) elif self.display_type == self.DISPLAY_TAG: context = {'tags': Tag.all_tags()} return render_to_string('config/blocks/sidebar_tags.html', context)
def GET(self,tags=None): try: all=self.param('all') except: all=False if(all): entries = Entry.all().order('-date') filename='micolog.%s.xml'%datetime.now().strftime('%Y-%m-%d') else: str_date_begin=self.param('date_begin') str_date_end=self.param('date_end') try: date_begin=datetime.strptime(str_date_begin,"%Y-%m-%d") date_end=datetime.strptime(str_date_end,"%Y-%m-%d") entries = Entry.all().filter('date >=',date_begin).filter('date <',date_end).order('-date') filename='micolog.%s.%s.xml'%(str(str_date_begin),str(str_date_end)) except: self.render2('views/admin/404.html') cates=Category.all() tags=Tag.all() self.response.headers['Content-Type'] = 'binary/octet-stream'#'application/atom+xml' self.response.headers['Content-Disposition'] = 'attachment; filename=%s'%filename self.render2('views/wordpress.xml',{'entries':entries,'cates':cates,'tags':tags})
def page(request, pk=-1): length = Diary.objects.count() try: diary = Diary.objects.get(pk=pk) except: diary = Diary.objects.last() length = -1 data = json.loads(serializers.serialize('json', [ diary, ]))[0] pk = data['pk'] data = data['fields'] data['subject'] = Subject.get_name(data['subject']) data['location'] = Location.get_name(data['location']) data['pk'] = pk try: data['next'] = Diary.objects.filter( id__gt=pk).order_by('id').first().id except: pass try: data['prev'] = Diary.objects.filter( id__lt=pk).order_by('-id').first().id except: pass data['len'] = length for i in range(len(data['with_me'])): data['with_me'][i] = WithMe.get_name(data['with_me'][i]) for i in range(len(data['tags'])): data['tags'][i] = Tag.get_name(data['tags'][i]) return JsonResponse(data)
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 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 save_tags(tags): """ Tags 数据库插入 :param tags: list tags :return: null """ if tags: for tag in tags: t = None try: t = Tag.objects.get(name=tag) except Exception: pass if not t: t = Tag(name=tag) t.save()
def blog_processor(request=None): # Loads category and tag information for displaying posts = Post.objects.filter(featured=True, is_project=False) posts = sorted(posts, key=lambda post: post.added, reverse=True) categories = Category.objects.all() tags = Tag.objects.all() cloud = Tag.generateCloud(tags) t = loader.get_template('tag_link.html') out = "" for tag, count in cloud.items(): c = Context({ "tag": tag }) if count >= 10: c.update({"tag_class": "biggest"}) elif count >= 6: c.update({"tag_class": "big"}) elif count >= 4: c.update({"tag_class": "medium"}) elif count >= 2: c.update({"tag_class": "small"}) else: c.update({"tag_class": "smallest"}) if count == 0: continue out += t.render(c) return {"featured": posts, "categories": categories, "tag_cloud": out, 'page_id': 'blog'}
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_tag_put(self): tag = Tag() tag.name = 'a' db.session.add(tag) db.session.commit() r = self.client.put( self.url + '/tag', data=json.dumps({ 'id': 1, 'name': 'b', 'article_ids': [] }), content_type='application/json', headers={"Authorization": "Bearer {}".format(self.get_token())}) self.assertEqual(r.status_code, 200) self.assertTrue(Tag.query.get(1).name == 'b')
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 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 setTags(entry, tags): if tags is None: entry.tags = [] else: try: # Check if we got a movable type style category array of structs if type(tags[0]) == dict: # We have a MT style list of IDs. tags = getTagsFromMT(tags) except: pass # Create any tags that don't exist yet, and then add them to the entry for tag in tags: if len(Tag.objects.filter(tag__iexact=tag)) == 0: new_tag = Tag() new_tag.tag = tag new_tag.save() entry.tags = [Tag.objects.get(tag__iexact=tag) for tag in tags]
def tags(request): tags = Tag.get_tags_by_priority() return render_to_response( "tags.html", { "page_title": ugettext("Tags"), "tags": tags, }, context_instance=RequestContext(request), )
def save_new_review_article(request): if request.method == 'POST' and request.user.is_authenticated(): form = AddArticleForm(request.POST) work_id = request.POST.get('work_id') work = Work.objects.get(pk=work_id) artist = work.creator if form.is_valid(): article = form.save() author = Author.objects.filter(user=request.user)[0] article.author = author article.work_link = work article.artist_link = artist article.save() tags_string = request.POST.get('tags') tags_list = tags_string.split(',') tags = [] for tag in tags_list: tags.append(tag.strip().lower().replace('-', ' ').replace('_', ' ')) # A Tag is another model, linked to the "article" via a ManyToMany field # Here we check to see if the user has entered tags that already exist in the database for tag in tags: pre_existing_tags = Tag.objects.filter(tag_name=tag) if len(pre_existing_tags) > 0: pre_existing_tag = pre_existing_tags[0] article.tags.add(pre_existing_tag) article.save() else: #create a new tag, save it to the DB, and add it to the article new_tag = Tag() new_tag.tag_name = tag new_tag.save() article.tags.add(new_tag) article.save() return HttpResponseRedirect('/wc_admin/view_article/?id=' + str(article.id)) else: error_message = 'The form was not valid. The data was not saved.' return render(request, 'blog/error.html', {'error_message': error_message, 'form': form}) else: error_message = 'The info was not properly posted. The data was not saved.' return render(request, 'blog/error.html', {'error_message': error_message})
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() # Log in self.client.login(username='******', password="******") # Check response code response = self.client.get('/admin/blogengine/post/add/') self.assertEquals(response.status_code, 200) # Create the new post response = self.client.post('/admin/blogengine/post/add/', { 'title': 'My first post', 'text': 'This is my first post', 'pub_date_0': '2013-12-28', 'pub_date_1': '22:00:04', 'slug': 'my-first-post', 'site': '1', 'category': '1', 'tags': '1' }, follow=True ) self.assertEquals(response.status_code, 200) # Check added successfully self.assertTrue('added successfully' in response.content) # Check new post now in database all_posts = Post.objects.all() self.assertEquals(len(all_posts), 1)
def clean_gae(): query = Entry.all() entries =query.fetch(1000) db.delete(entries) query = Country.all() countries = query.fetch(1000) db.delete(countries) query = Tag.all() tags = query.fetch(1000) db.delete(tags)
def add_post(request): try: if not request.user.is_authenticated(): return HttpResponseRedirect('/login') template = 'blog/add-post.html' args = {} if request.method == 'POST': form = NewPostForm(request.POST) if form.is_valid(): visible = True if form.cleaned_data['visible'] == 'public' else False new_post = Post(user=request.user, title=form.cleaned_data['title'], body=form.cleaned_data['body'], visible=visible,) new_post.save() tags = form.cleaned_data['tags'].split() existing_tags = [tag.tag for tag in Tag.objects.all()] for tag in tags: if tag not in existing_tags: new_tag = Tag(tag=tag) existing_tags.append(tag) new_tag.save() else: new_tag = Tag.objects.get(tag__contains=tag) new_post.tag.add(new_tag) return HttpResponseRedirect('/' + request.user.username + '/post' + str(new_post.id)) else: form = NewPostForm() args.update({'form': form}) except Exception as e: e = str(e) raise Http404(e) return render_to_response(template, args, context_instance=RequestContext(request))
def admin_list_tag(request): if users.is_current_user_admin(): return object_list(request, template_object_name='obj', queryset=Tag.all(), allow_empty=True, extra_context={'type': 'tag'}, template_name='admin/list.html', paginate_by=setting.ADMIN_LIST_PER_PAGE, ) else: return HttpResponseRedirect('/')
def test_create_tag(self, tag): u,p,tag = tag assert Post.find_by_id(1) assert Tag.find_by_id(1) assert Persion.find_by_id(1) assert tag.posts[0] == p assert tag.name == tag_name assert p.name == post_name assert p.body == post_body assert p.author == u assert p.author.name == persion_name assert p.author.email == persion_email assert p.author.password == persion_pwd
def test_delete_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="******") # Delete the tag response = self.client.post('/admin/blogengine/tag/1/delete/', { 'post': 'yes' }, follow=True) self.assertEquals(response.status_code, 200) # Check deleted successfully self.assertTrue('deleted successfully' in response.content) # Check tag deleted all_tags = Tag.objects.all() self.assertEquals(len(all_tags), 0)