本文整理汇总了Python中blog.models.Article类的典型用法代码示例。如果您正苦于以下问题:Python Article类的具体用法?Python Article怎么用?Python Article使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Article类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: ajax_editor
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)
示例2: test_validate_account
def test_validate_account(self):
site = Site.objects.get_current().domain
user = BlogUser.objects.create_superuser(email="[email protected]",
username="liangliangyy1", password="liangliangyy1")
self.client.login(username='liangliangyy1', password='liangliangyy1')
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)
示例3: create
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, )))
示例4: article_create
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)
示例5: edit
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('/')
示例6: article_create
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))
示例7: post
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')
示例8: test_slug_field_should_automatically_slugify_title
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')
示例9: test_est_recent_avec_futur_article
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)
示例10: article
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/')
示例11: get_context_data
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
示例12: test_validate_comment
def test_validate_comment(self):
site = Site.objects.get_current().domain
user = BlogUser.objects.create_superuser(email="[email protected]",
username="liangliangyy1", password="liangliangyy1")
self.client.login(username='liangliangyy1', password='liangliangyy1')
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()
示例13: create
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)
示例14: submit
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')
示例15: dealWithArticle
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))