def post(self, request, format=None): try: ser = SubmitAricleSerializer(data=request.data) if ser._valid(): title = ser.data.get('title') cover = request.FILES['cover'] content = ser.data.get('content') category_id = ser.data.get('category_id') author_id = ser.data.get('author_id') promote = ser.data.get('promote') else: return Response({'status':'Bad request ...', status=status.HTTP_200_OK}) user = User.objects.get(id=author_id) author = UserProfile.objects.get(user=user) category = Category.objects.get(id=category_id) article = Article() article.title = title article.cover = cover article.content = content article.category = category article.author = author article.promote = promote article.save() return Response('status':'OK', status = status.HTTP_200_OK) except: return Response({'status': 'server error .....'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
def test_validate_comment(self): site = Site.objects.get_current().domain user = BlogUser.objects.create_superuser(email="*****@*****.**", username="******", password="******") self.client.login(username='******', password='******') c = Category() c.name = "categoryccc" c.created_time = datetime.datetime.now() c.last_mod_time = datetime.datetime.now() c.save() article = Article() article.title = "nicetitleccc" article.body = "nicecontentccc" article.author = user article.category = c article.type = 'a' article.status = 'p' article.save() s = TextMessage([]) s.content = "nicetitleccc" rsp = search(s, None) self.assertTrue(rsp != '没有找到相关文章。') rsp = category(None, None) self.assertIsNotNone(rsp) rsp = recents(None, None) self.assertTrue(rsp != '暂时还没有文章') cmd = commands() cmd.title = "test" cmd.command = "ls" cmd.describe = "test" cmd.save() cmdhandler = CommandHandler() rsp = cmdhandler.run('test') self.assertIsNotNone(rsp) s.source = 'u' s.content = 'test' msghandler = MessageHandler(s, {}) #msghandler.userinfo.isPasswordSet = True #msghandler.userinfo.isAdmin = True msghandler.handler() s.content = 'y' msghandler.handler() s.content = 'idcard:12321233' msghandler.handler() s.content = 'weather:上海' msghandler.handler() s.content = 'admin' msghandler.handler() s.content = '123' msghandler.handler() s.content = 'exit' msghandler.handler()
def create_new_article(request): # form = ArticleForm() # context = {'form': form} # response = render(request, 'new_article.html', context) # return HttpResponse(response) # form = ArticleForm(request.POST) # if form.is_valid(): # new_article = form.save() # return HttpResponseRedirect('/home') # else: # context = { 'form': form } # response = render(request, 'new_article.html', context) # return HttpResponse(response) if request.method == 'POST': article = Article(user=request.user) article.user = request.user form = ArticleForm(request.POST, instance=article) if form.is_valid(): instance = form.save(commit=False) instance.user = request.user instance.save() # instance.user = request.user # create_new_article = form.save() return HttpResponseRedirect('/home') else: context = {'form': form} response = render(request, 'new_article.html', context) return HttpResponse(response) else: form = ArticleForm() context = {'form': form} response = render(request, 'new_article.html', context) return HttpResponse(response)
def createArticle(request): if request.method == 'POST': form = ArticleForm(request.POST) if form.is_valid(): cleaned_data = form.cleaned_data a = Article(titre=cleaned_data['titre'], content=cleaned_data['content'], auteur=request.user, categorie=cleaned_data['categorie']) a.save() contenttype = ContentType.objects.get(app_label='blog', model='Article') perm1 = Permission.objects.create( codename='change_article_%d' % a.id, name="Modifier l'article %d" % a.id, content_type=contenttype) perm2 = Permission.objects.create( codename='delete_article_%d' % a.id, name="Supprimer l'article %d" % a.id, content_type=contenttype) request.user.user_permissions.add(perm1) request.user.user_permissions.add(perm2) messages.success( request, 'L\'article "%s" a bien été ajouté !' % cleaned_data['titre']) return redirect(reverse('article_by_slug', kwargs={'slug': a.slug})) form = ArticleForm(request.POST or None) return render(request, 'blog/article_form.html.twig', locals())
def article_admin(request): if request.method == 'GET': tag_id = request.GET.get('tag') if tag_id and tag_id != 'undefined': article_list = Article.objects.all().filter( tag__id=int(tag_id)).order_by('-id') tag_info = Tag.objects.get(id=int(tag_id)) serializer = ArticleSerializer(article_list, many=True) tag_serializer = TagSerializer(tag_info) data = { 'article_data': serializer.data, 'tag_data': tag_serializer.data } return Response(data, status=status.HTTP_200_OK) else: article_list = Article.objects.all().order_by('-id') serializer = ArticleSerializer(article_list, many=True) return Response(serializer.data, status=status.HTTP_200_OK) if request.method == 'POST': data = request.data title = data.get('title') content = data.get('content') # 取出内容中markdown的图片地址作为首页图片 img_url = re.search('!\[]\((.*?)\)', content) if not img_url: img_url = '' else: img_url = img_url.group(1) art = Article(title=title, content=content, url_img=img_url) art.save() return Response(status=status.HTTP_200_OK)
def article(request): if request.user.is_authenticated: # GET api/article Response with a JSON having a list of dictionaries for each article's # title, content, and author. The value of the author must be the id of the author. if request.method == 'GET': def toDict(article): return { 'title': article['title'], 'content': article['content'], 'author': article['author_id'] } article_list_obj = Article.objects.all().values() article_list = [toDict(article) for article in article_list_obj] return JsonResponse(article_list, safe=False) # POST api/article Create an article with the information given by request JSON body # and response with 201 elif request.method == 'POST': try: body = request.body.decode() title = json.loads(body)['title'] content = json.loads(body)['content'] except (KeyError, JSONDecodeError) as e: return HttpResponseBadRequest() # 400 new_article = Article(title=title, content=content, author=request.user) new_article.save() return HttpResponse('Posted', status=201) else: return HttpResponseNotAllowed(['GET', 'POST']) # 405 else: return HttpResponse('Unautenticated', status=401)
def test_first_page_default(self): """ Test that the first page is returned by default. """ create_articles(11) self.assertEqual(Article.get_articles()[0], Article.get_articles(page=1)[0])
def test_validate_account(self): site = Site.objects.get_current().domain user = BlogUser.objects.create_superuser(email="*****@*****.**", username="******", password="******") self.client.login(username='******', password='******') response = self.client.get('/admin/') self.assertEqual(response.status_code, 200) category = Category() category.name = "categoryaaa" category.created_time = datetime.datetime.now() category.last_mod_time = datetime.datetime.now() category.save() article = Article() article.title = "nicetitleaaa" article.body = "nicecontentaaa" article.author = user article.category = category article.type = 'a' article.status = 'p' article.save() response = self.client.get(article.get_admin_url()) self.assertEqual(response.status_code, 200)
def setUpTestData(cls): cls.articles = [] cls.articles.append(Article(pub_date='2018-02-13 18:17:16')) cls.articles.append(Article(pub_date='2018-02-13 18:18:13')) cls.articles.append(Article(pub_date='2018-02-13 18:20:26')) Article.objects.bulk_create(cls.articles)
def article_create(): form = ArticleCreateForm() form.category_id.choices = Category.choices() if request.method == 'POST' and form.validate(): if not g.user.is_admin(): flash(u'非管理员不能创建文章!') return redirect(url_for('index')) else: nowtime = datetime.datetime.now() article = Article(title=form.title.data, body=form.body.data, user_id=g.user.id, category_id=form.category_id.data, text=request.form.get('textformat'), timestamp=nowtime, tag=form.tag.data, is_open=form.is_open.data) article.post_date = nowtime db.session.add(article) db.session.commit() flash(u'文章已创建!') Blog_info.new_article() return redirect(url_for('article_edit', id=article.id)) return render_template('article_create.html', title=u'创建文章', form=form)
def create(request): new_article = Article( title=request.POST['title'], body=request.POST['body'], created_date=datetime.datetime.now()) new_article.save() return HttpResponseRedirect(reverse('blog:detail', args=(new_article.id, )))
def ajax_editor(request): # 保存文章 # 获取作者 user = request.user if not user: msg = "error|无法获取作者" else: # 获取前段数据 try: html = request.POST.get("html","") title = request.POST.get("title","") tag = request.POST.get("tag","") keys = request.POST.get("keys","") id = request.POST.get("id","") except Exception as e: print(e) msg = u"error|前端数据获取失败" print msg else: # 前端没有id传过来则新建 # 有id传过来则更新 if not id: # script过滤 html = re_js(html) title = re_js(title) tag = re_js(tag) keys = re_js(keys) try: article = Article(title=title, user = user, article_class=tag, keyword=keys, content = html) article.save() except Exception as e: print(e) msg = "error|文章保存失败" else: msg = "ok|保存成功" else: try: article = Article.objects.filter(id=id) # 权限检查 操作和数据库中记录的用户不是一个人则抛出异常,无权修改.超级管理员有权修改 if article[0].user == user or user.is_superuser: article.update(title=title, user = user, article_class=tag, keyword=keys, content = html) else: msg ="error|你没有修改权限" print(msg) raise Exception(msg) except Exception as e: print(e) msg = "error|更新失败" else: msg = "ok|更新成功" return HttpResponse(msg)
def savePost(request): """ Saves a post, new or modified Checks if user is admin """ if request.user.is_superuser: # Calculates checkboxes values draft= True if (request.POST.get('draft', False)=="on" or request.POST.get('draft', False)=="checked") else False commentable= True if (request.POST.get('commentable', False)=="on" or request.POST.get('commentable', False)=="checked") else False article_id = request.POST.get('article_id', False) if article_id: # Modification p = get_object_or_404(Article, pk=article_id) p.title=request.POST['title'] p.content=request.POST['content'] p.draft=draft p.date = parse_date(request.POST['date']) p.commentable = commentable else: # New article p = Article(title=request.POST['title'], content=request.POST['content'], draft=draft, date = parse_date(request.POST['date']), commentable=commentable) p.save() return HttpResponseRedirect(reverse('blog:admin')) else: return HttpResponseForbidden()
def edit(request): if request.method == 'GET': if 'arid' in request.GET: context = {} arid = request.GET['arid'] article = Article.objects.filter(id=arid)[0] context['art'] = article return render(request,'edit.html',context) elif 'username' in request.session: context = {} context['name'] = Constant.BLOG_NAME return render(request,'edit.html',context) else: return HttpResponseRedirect('/') else:#POST commit if 'id' in request.POST: article = Article.objects.get(id=request.POST['id']) article.title = request.POST['title'] article.content = request.POST['content'] article.save() return HttpResponseRedirect('/') else: un = _get_name(request) article = Article(title=request.POST['title'] ,author=un,date=time.strftime('%Y-%m-%d',time.localtime(time.time())),content=request.POST['content']) article.save() return HttpResponseRedirect('/')
def database(): # Create a temporary db before the test _, file_name = tempfile.mkstemp() os.environ['DATABASE_NAME'] = file_name Article.create_table(database_name=file_name) yield # Delete the temporary db after the test os.unlink(file_name)
def database(): # do something before your test _, file_name = tempfile.mkstemp() os.environ['DATABASE_NAME'] = file_name Article.create_table(database_name=file_name) yield # tests runs here # do something after your test os.unlink(file_name)
def article_create(request): title = request.POST.get('title', '') content = request.POST.get('content', '') author = Author.objects.get(name=request.session["author_name"]) article = Article(title=title, content=content, author=author) article.save() articles = Article.objects.order_by('id') return render_to_response('articles/index.html', {'articles': articles}, context_instance=RequestContext(request))
def deal(request): if request.method == "POST": title = request.POST.get('title') content = request.POST.get('content') article = Article(title=title, content=content) article.save() ret = {"ret": 0, 'title': title, 'content': content} return HttpResponse(json.dumps(ret))
def setUpTestData(cls): tag = Tag.objects.create(name=set('Fruit',)) tag.save() user = User() user.save() article = Article( title='New article') article.(tag, user,) article.save() Comment.objects.create(user=User, email='*****@*****.**', name='Nik', text='Some text', article='New article')
def create_article(article_details): new_article = Article(title=article_details["title"], slug=article_details["url"], content=article_details["content"]) new_article.save() for tag in article_details["tags"]: new_article.tags.add(tag)
def test_doesnt_return_unpublished(self): """ Test that only published articles are returned, and unpublished articles are left out. """ published_article = Article.objects.create(published=True) Article.objects.create(published=False) self.assertEqual(len(Article.get_articles()), 1) self.assertEqual(published_article, Article.get_articles()[0])
def submit(request): try: cont = request.POST['content'] except (KeyError): return render(request, 'blog/index.html', context={'all_articles': all_articles, 'message': 'Write something!'}) else: article = Article(content=cont, written_date=timezone.now()) article.save() return HttpResponseRedirect('/blog')
def post(self): from blog.forms import AddContentModalForm from auth.models import User self._form = AddContentModalForm(request.form) from blog.models import Article a = Article() self._form.populate_obj(a) a.author = User.query.filter(User.email==session.get('email',None)).first() a.save() return self.redirect('blog.index')
def test_est_recent_avec_futur_article(self): """ Vérifie si la méthode est_recent d'un Article ne renvoie pas True si l'Article a sa date de publication dans le futur. """ futur_article = Article(date=datetime.now() + timedelta(days=20)) # Il n'y a pas besoin de remplir tous les champs, ni de sauvegarder self.assertEqual(futur_article.est_recent(), False)
def test_pagination(self): """ Test that articles are returned in pages, with the first page containing the most recent articles. """ create_articles(11) second_article = Article.get_articles(page=1)[9] first_article = Article.get_articles(page=2)[0] self.assertEqual(second_article.id, 2) self.assertEqual(first_article.id, 1)
def article(request): title = request.POST['title'] author = request.POST['author'] body = request.POST['body'] usernameid = request.session['person_id'] headImg = request.FILES['upload'] uploadedfile(headImg) art = Article(title=title,author=author,body=body,usernameid=usernameid,headImg=headImg) art.save() return HttpResponseRedirect('/blog/')
def test_slug_field_should_automatically_slugify_title(self): user = UserFactory.create() article = Article( title='This is a title', author=user, content='Blah blah some content' ) article.save() article.slug | should | equal_to('this-is-a-title')
def test_delete_post(self): # Create the post post = Article() post.name = 'My first post' post.slug = 'my-first-post' post.short_content = 'This is my first blog post' post.content = 'This is my first blog post' post.published = True post.save() # Check new post saved all_posts = Article.objects.all() self.assertEquals(len(all_posts), 1) # Log in self.client.login(username='******', password="******") # Delete the post response = self.client.post('/admin/blog/article/2/delete/', {'post': 'yes'}, follow=True) self.assertEquals(response.status_code, 200) # Check deleted successfully self.assertTrue(b'Select article to change' in response.content) # Check post amended all_posts = Article.objects.all() self.assertEquals(len(all_posts), 0)
def test_edit_post(self): # Create the post post = Article() post.name = 'My first post' post.slug = 'my-first-post' post.short_content = 'This is my first blog post' post.content = 'This is my first blog post' post.published = True post.save() # Log in self.client.login(username='******', password="******") # Edit the post response = self.client.post('/admin/blog/article/3/', { 'name': 'My second post', 'slug': 'my-second-post', 'short_content': 'This is my second blog post', 'content': 'This is my second blog post', }, follow=True) self.assertEquals(response.status_code, 200) # Check changed successfully self.assertTrue(b'Select article to change' in response.content) # Check post amended all_posts = Article.objects.all() self.assertEquals(len(all_posts), 1) only_post = all_posts[0] self.assertEquals(only_post.name, 'My second post') self.assertEquals(only_post.content, markdown('This is my second blog post'))
def submit(request): try: cont = request.POST['content'] except (KeyError): return render_to_response('index.html', {'all_articles' : all_articles, 'message' : 'Failed to read content'}, context_instance=RequestContext(request)) else: article = Article(content=cont, written_date=timezone.now()) article.save() return HttpResponseRedirect('/blog')
def test_articles(self): article = Article() article.title = 'a' article.slug = 'skg' article.content = 'content xxx' db.session.add(article) db.session.commit() r = self.client.get(self.url + '/articles?page=1', ) self.assertEqual(r.status_code, 200) r = self.client.get(self.url + '/articles?page=-1', ) self.assertEqual(r.status_code, 404)
def create(request): title = request.POST.get('title') content = request.POST.get('content') form = ArticleForm(dict(title=title, content=content,)) if form.is_valid(): article = Article(title=title, content=content,) article.save() #else: #return return redirect(show, article_id=article.id)
def get_context_data(self, **kwargs): """ Loads common information that is needed throughout the website. First it gets blog information, that is, getting articles by year and month, and articles by tag. Then adds email and google recaptcha keys to compose the context data that will be passed to all the views. Arguments: **kwargs: Django's default kwargs for this overridden function. """ # Populate entries by time line info. entries_by_time_line = [] for active_year in Article.active_years(): articles_per_year = Article.articles_per_year(active_year) month_list = [] for active_month in Article.active_months_per_year(active_year): articles = Article.articles_per_month_and_year( active_year, active_month ) articles_list = [] for article in articles: articles_list.append((article.id, article.title)) month_list.append(( active_month, MONTHS_OF_THE_YEAR[active_month], articles.count(), articles_list )) entries_by_time_line.append((active_year, articles_per_year.count(), month_list)) # Populate entries by tag info. entries_by_tag = [] for tag in Tag.objects.all(): articles = tag.related_articles.all() articles_list = [] for article in articles: articles_list.append((article.id, article.title)) entries_by_tag.append((tag.name, tag.__str__(), articles.count(), articles_list)) # Update context dictionary with the previous information and email # and google recaptcha settings. context = super(ContextMixin, self).get_context_data(**kwargs) app_context = { 'email': settings.DEFAULT_FROM_EMAIL, 'google_recaptcha_client_key': settings.GOOGLE_RECAPTCHA_CLIENT_KEY, 'entries_by_time_line': entries_by_time_line, 'entries_by_tag': entries_by_tag } context.update(app_context) return context
def test_list_articles(): Article(author='*****@*****.**', title='New Article', content='Super extra awesome article').save() Article(author='*****@*****.**', title='Another Article', content='Super awesome article').save() query = ListArticlesQuery() assert len(query.execute()) == 2
def main(): user = User.objects.all()[0] categories = Category.objects.all() for i in range(1000): article = Article( slug=f'article_{i}', title=f'Article Title {i}', content=CONTENT_STRING, user=user, ) article.save()
def post(self): from blog.forms import AddContentModalForm from auth.models import User self._form = AddContentModalForm(request.form) from blog.models import Article a = Article() self._form.populate_obj(a) a.author = User.query.filter( User.email == session.get('email', None)).first() a.save() return self.redirect('blog.index')
def test_validate_comment(self): site = Site.objects.get_current().domain user = BlogUser.objects.create_superuser(email="*****@*****.**", username="******", password="******") self.client.login(username='******', password='******') c = Category() c.name = "categoryccc" c.created_time = datetime.datetime.now() c.last_mod_time = datetime.datetime.now() c.save() article = Article() article.title = "nicetitleccc" article.body = "nicecontentccc" article.author = user article.category = c article.type = 'a' article.status = 'p' article.save() s = TextMessage([]) s.content = "nicetitleccc" rsp = search(s, None) self.assertTrue(rsp != '没有找到相关文章。') rsp = category(None, None) self.assertIsNotNone(rsp) rsp = recents(None, None) self.assertTrue(rsp != '暂时还没有文章') cmd = commands() cmd.title = "test" cmd.command = "ls" cmd.describe = "test" cmd.save() cmdhandler = CommandHandler() rsp = cmdhandler.run('test') self.assertIsNotNone(rsp) s.source = 'u' s.content = 'test' msghandler = MessageHandler(s, {}) #msghandler.userinfo.isPasswordSet = True #msghandler.userinfo.isAdmin = True msghandler.handler() s.content = 'y' msghandler.handler() s.content='idcard:12321233' msghandler.handler() s.content='weather:上海' msghandler.handler() s.content='admin' msghandler.handler() s.content='123' msghandler.handler() s.content = 'exit' msghandler.handler()
def execute(self) -> Article: try: Article.get_by_title(self.title) raise AlreadyExists except NotFound: pass article = Article(author=self.author, title=self.title, content=self.title).save() return article
def testdb(request): # 修改其中一个id=1的name字段,再save,相当于SQL中的UPDATE test1 = Article(title='老王的博客', content='这是老王的第一个博客', author_id=1) test1.save() # 另外一种方式 #Test.objects.filter(id=1).update(name='Google') # 修改所有的列 # Test.objects.all().update(name='Google') return HttpResponse("<p>修改成功</p>")
def _import_article(self, article_data): author = Author.objects.get(username=article_data['author']) article = Article(title=article_data['title'], content=article_data['content'], created_at=article_data['created_at'], author=author) article.save() tags = [] for tag in article_data['tags']: tag_instance, _ = Tag.objects.get_or_create(name=tag) tags.append(tag_instance) article.tags.add(*tags)
def test_validate_comment(self): site = get_current_site().domain user = BlogUser.objects.create_superuser( email="*****@*****.**", username="******", password="******") self.client.login(username='******', password='******') c = Category() c.name = "categoryccc" c.created_time = timezone.now() c.last_mod_time = timezone.now() c.save() article = Article() article.title = "nicetitleccc" article.body = "nicecontentccc" article.author = user article.category = c article.type = 'a' article.status = 'p' article.save() s = TextMessage([]) s.content = "nice" rsp = search(s, None) rsp = category(None, None) self.assertIsNotNone(rsp) rsp = recents(None, None) self.assertTrue(rsp != 'No articles yet') cmd = commands() cmd.title = "test" cmd.command = "ls" cmd.describe = "test" cmd.save() cmdhandler = CommandHandler() rsp = cmdhandler.run('test') self.assertIsNotNone(rsp) s.source = 'u' s.content = 'test' msghandler = MessageHandler(s, {}) # msghandler.userinfo.isPasswordSet = True # msghandler.userinfo.isAdmin = True msghandler.handler() s.content = 'y' msghandler.handler() s.content = 'idcard:12321233' msghandler.handler() s.content = 'weather:
def save(self): cd = self.cleaned_data name = cd['name'] cover = cd['cover'] type = cd['type'] content = cd['content'] tags = cd['tags'] article = Article(name=name, cover=cover, content=content, type=type, tags=tags) article.save()
def profile(username): try: user = User.objects.get(slug=username) except User.DoesNotExist: abort(404) if user == current_user: articles = Article.objects(author=user) else: articles = Article.objects(author=user, published=True) return render_template('user/profile.html', user=user, articles=articles, edit=(user == current_user))
def dealWithArticle(request, post_id=0): ''' если post_id = 0 => аргумент был не передан и мы создаем статью иначе редактируем статью с id = post_id надо будет прикрутить куки, чтобы... после редактирования статьи возвращать на страницу, откуда статья редактировалась. а после создания статьи возвращать страницу новосозданной статьи ''' if post_id == 0: #добавление статьи mode = 0 else: #редактирование статьи mode = 1 try: article = Article.objects.get(pk = post_id) article_form = ArticleForm(instance = article) article = article_form.save(commit = False) except Article.DoesNotExist: article = Article() if request.POST: post = request.POST.copy() new_article_form = ArticleForm(post) if new_article_form.is_valid(): new_article = new_article_form.save(commit = False) article.title = new_article.title article.bb_text = new_article.bb_text article.main_text = render_bbcode(new_article.bb_text) article.desc_text = render_bbcode(get_desc(new_article.bb_text)) article.pub_date = timezone.now() article.is_big = is_big(article.main_text) article.save() return HttpResponseRedirect(reverse('blog.views.post',kwargs={'post_id':article.id})) else: return render_to_response('article_form.html',{'article_form': new_article_form, 'mode':mode, 'url_ref': ref_for_article_form}, context_instance=RequestContext(request)) else: #добавляем статью if mode == 0: article_form = ArticleForm() return render_to_response('article_form.html',{'article_form': article_form, 'mode':mode, 'url_ref': ref_for_article_form}, context_instance=RequestContext(request)) if mode == 1: return render_to_response('article_form.html',{'article_form': article_form, 'mode':mode, 'url_ref': ref_for_article_form, 'article_id':article.id}, context_instance=RequestContext(request))
def article_update(request, year='', month='', day='', id=""): id = id if request.method == 'POST': form = ArticleForm(request.POST) tag = TagForm(request.POST) if form.is_valid() and tag.is_valid(): cd = form.cleaned_data cdtag = tag.cleaned_data tagname = cdtag['tag_name'] tagnamelist = tagname.split() for taglist in tagnamelist: Tag.objects.get_or_create(tag_name=taglist.strip()) title = cd['caption'] content = cd['content'] article = Article.objects.get(id=id) if article: article.caption = title article.content = content article.save() for taglist in tagnamelist: article.tags.add(Tag.objects.get(tag_name=taglist.strip())) article.save() tags = article.tags.all() for tagname in tags: tagname = unicode(str(tagname), "utf-8") if tagname not in tagnamelist: notag = article.tags.get(tag_name=tagname) article.tags.remove(notag) else: article = Article(caption=article.caption, content=article.content) article.save() return HttpResponseRedirect('/blog/article/%s/%s/' % ('/'.join(str(article.publish_time).split()[0].split('-')), id)) else: try: article = Article.objects.get(id=id) if [year, month, day] != str(article.publish_time).split()[0].split('-'): raise Article.DoesNotExist except Exception: raise Http404 tags = article.tags.all() if tags: taginit = '' for x in tags: taginit += str(x) + ' ' tag = taginit else: tag = '' return render_to_response('article_add.html', {'article': article, 'id': id, 'tag': tag}, context_instance=RequestContext(request))
def test_active_months_per_year(self): """ Tests the active_months_per_year function. """ self.assertEqual(Article.active_months_per_year(2011), []) Article.objects.create(published=datetime.datetime( 2011, 3, 12, 0, 0, 0, 0, get_current_timezone())) self.assertEqual(Article.active_months_per_year(2011), [3]) Article.objects.create(published=datetime.datetime( 2011, 3, 4, 0, 0, 0, 0, get_current_timezone())) self.assertEqual(Article.active_months_per_year(2011), [3]) Article.objects.create(published=datetime.datetime( 2011, 12, 11, 0, 0, 0, 0, get_current_timezone())) self.assertEqual(Article.active_months_per_year(2011), [12, 3])
def create_article(author, save=True): article = Article( author=author, title="Some Article", slug="some-article", active=True, content="**Here** is *some text*", creation_date=make_time(2015, 6, 1, 3, 4, 7), modified_date=make_time(2015, 6, 1, 3, 4, 7), ) if save: article.save() return article
def update_article(request, id): """Enables Article update""" article = Article.get_by_id(int(id)) if article: if request.method == 'POST': form = ArticleForm(request.POST) if form.is_valid(): article.title = form.cleaned_data['title'] article.content = form.cleaned_data['content'] article.put() messages.add_message(request, messages.INFO, u'Article %s created' % form.cleaned_data['title']) time.sleep(1) return redirect('home') else: form = ArticleForm({'title': article.title, 'content': article.content}) return render(request, 'article/create.html', locals()) else: messages.add_message(request, messages.ERROR, u'Article not found') return redirect('home')
def calendar_json(): arg = request.args start, stop = arg['start'], arg['end'] create_article = Article.query.filter(Article.post_date >= start).filter(Article.post_date <= stop).all() update_article = Article.find_edit(start, stop) visit = Blog_info.query.all() data = [] for a in create_article: dic = { 'title': u'新增文章' + a.title, 'url': '/article_show/' + a.title, 'start': str(a.post_date) } data.append(dic) for a in update_article: dic = { 'title': u'更新文章' + a.title, 'url': '/' + a.title, 'start': str(a.timestamp) } data.append(dic) for v in visit: dic = { 'title': u'日访问量:' + str(v.visit_day), 'start': str(v.date) } data.append(dic) return json.dumps(data)
def articles_page(request, curr_work=None): c = get_common_context(request) if curr_work: c['curr_article'] = Article.get_by_slug(curr_work) return render_to_response('article.html', c, context_instance=RequestContext(request)) else: c['articles'] = Article.objects.all() return render_to_response('articles.html', c, context_instance=RequestContext(request))
def test_active_years(self): """ Tests the active_years function. """ self.assertEqual(Article.active_years(), []) Article.objects.create(published=datetime.datetime( 2009, 3, 12, 0, 0, 0, 0, get_current_timezone())) self.assertEqual(Article.active_years(), [2009]) Article.objects.create(published=datetime.datetime( 2011, 12, 4, 0, 0, 0, 0, get_current_timezone())) self.assertEqual(Article.active_years(), [2011, 2009]) Article.objects.create(published=datetime.datetime( 2011, 2, 11, 0, 0, 0, 0, get_current_timezone())) self.assertEqual(Article.active_years(), [2011, 2009]) Article.objects.create(published=datetime.datetime( 2015, 4, 3, 0, 0, 0, 0, get_current_timezone())) self.assertEqual(Article.active_years(), [2015, 2011, 2009])
def search_result(sch, page=1): try: result = Article.search(st=sch, page=page, num=5) except: result = None return render_template("search_result.html", title=u'搜索:' + sch, search=sch, article=result)
def index(categoryname='all', month='all', page=1): category = Category.query.filter_by(is_use=1).order_by(Category.seq) article = Article.article_per_page(categoryname, month, page) return render("index.html", title='Home', article=article, category=category, categoryname=categoryname, month=month)
def get_article(self, slug): """ Get article """ article = Article.get_by_key_name(slug) if article: self.response.out.write(template.render( 'blog/templates/article.html', {'article': article})) else: self.redirect('/')
def get_common_context(request): c = {} c['request_url'] = request.path c['works_r'] = Work.get_recent(4) c['works_b'] = Work.get_best(4) c['articles_r'] = Article.get_recent(4) c['is_debug'] = settings.DEBUG c.update(csrf(request)) return c
def add_article(request): if request.method == 'POST': if not request.user.is_authenticated() or not request.user.is_staff or not request.user.is_active: return HttpResponseRedirect('/') form = ArticleForm(request.POST) if form.is_valid(): title = form.cleaned_data['title'] slug = form.cleaned_data['slug'] text = form.cleaned_data['text'] article=Article(title=title, slug=slug, text=text, user=request.user) article.save() return HttpResponseRedirect('/') else: form = ArticleForm() return render_to_response('blog/add_article.html', { 'form': form, },context_instance=RequestContext(request))
def blog_more(request, page_name=None): if page_name: c = get_common_context(request) c['a'] = BlogArticle.get_by_slug(page_name) c['articles'] = BlogArticle.objects.all() c['base_url'] = 'blog' c['base_title'] = u'Блог' return render_to_response('articles_more.html', c, context_instance=RequestContext(request)) else: return HttpResponseRedirect('/blog/%s/' % BlogArticle.objects.all()[0].slug)
def addArticle(request): categories=Category.objects.all(); if request.method=='POST': form=ArticleForm(request.POST,request.FILES) if form.is_valid(): title=form.cleaned_data['title'];summary=form.cleaned_data['summary'];paragraph=form.cleaned_data['paragraph'] caption=form.cleaned_data['caption'];link=form.cleaned_data['link'];linkText=form.cleaned_data['linkText']; image=form.cleaned_data['image'];category=form.cleaned_data['category']; envoi=True #creation of the section object article=Article(title=title,summary=summary,paragraph=paragraph,caption=caption,image=image,link=link,linkText=linkText) article.category=category; article.save(); return home(request); #return page(request,category); else: addArticle=True; displayForm=True; form=ArticleForm() return render(request, 'blog/blogForm.html',locals())
def before_request(): g.search_form = SearchForm() g.user = current_user g.info = Blog_info.info() g.first_bar = Settings.first_bar() g.count = Article.count_by_month() g.top_five = Article.top(10) if g.user.is_authenticated(): g.user.last_seen = datetime.datetime.now() db.session.add(g.user) db.session.commit() g.list_bar = Settings.admin_second_bar() if request.url.find('static') < 0 and request.url.find('favicon.ico') < 0: agent = request.headers['User-Agent'] url = request.base_url log = Visit_log(timestamp=datetime.datetime.now(), ip=request.remote_addr, url=url, agent=agent) db.session.add(log) db.session.commit()