本文整理汇总了Python中models.Article.save方法的典型用法代码示例。如果您正苦于以下问题:Python Article.save方法的具体用法?Python Article.save怎么用?Python Article.save使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类models.Article
的用法示例。
在下文中一共展示了Article.save方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: submitarticle
# 需要导入模块: from models import Article [as 别名]
# 或者: from models.Article import save [as 别名]
def submitarticle(request):
error_msg = u"No POST data sent."
if request.method == "POST":
post = request.POST.copy()
if post.has_key('tags') and post.has_key('title') and post.has_key('url'):
try:
url = post['url']
art = Article()
art.tags = post['tags'].strip().split(',')
art.author = str(request.user)
art.title = post['title']
art.votecount = 0
art.viewcount = 0
if not url.startswith('http://'):
url = 'http://'+url
art.url = url
if art.url and art.title and art.author:
try:
person = getPerson(request)
person.timesArticle = person.timesArticle + 1
person.lastActive = datetime.datetime.now()
rating = Score.objects(type='submitarticle')[0].value
person.currentRating = person.currentRating + rating
person.save()
incrementStat('articles',1)
art.save()
except Exception as inst:
print inst
return HttpResponseRedirect('/')
except:
return HttpResponseServerError('wowza! an error occurred, sorry!')
else:
error_msg = u"Insufficient POST data (need 'content' and 'title'!)"
return HttpResponseServerError(error_msg)
示例2: save_article
# 需要导入模块: from models import Article [as 别名]
# 或者: from models.Article import save [as 别名]
def save_article(request, page_name):
continent_list = dropdown()
page_content = request.POST['Content']
continent_content = request.POST['continent_rad']
try:
article = Article.objects.get(article_title=page_name)
except Article.DoesNotExist:
author = request.user
authorname = author.username
article = Article(article_title = page_name,
article_continent = continent_content,
article_author= authorname)
article.save()
content_author = request.user
content_author_name=content_author.username
content = Content(content_content= page_content,
content_article= article,
content_change_date= datetime.now(),
content_author=content_author_name)
content.save()
article.article_last_revision = content
article.save()
return HttpResponseRedirect("/wikijourney/" + page_name + "/")
示例3: create_new_content
# 需要导入模块: from models import Article [as 别名]
# 或者: from models.Article import save [as 别名]
def create_new_content(idx):
author = users[random.randrange(0, len(users) - 1)]
created_at = datetime.datetime.utcnow() - datetime.timedelta(hours=3 * idx)
type = (
CONTENT_TYPE.ARTICLE
if author["type"] == "public"
else random.choice([CONTENT_TYPE.ARTICLE, CONTENT_TYPE.PROJECT])
)
loc = choose_loc()
doc = {
"type": type,
"title": unicode(titles[random.randrange(0, len(titles) - 1)]),
"content": unicode(contents[random.randrange(0, len(contents) - 1)]),
"tags": choose_tags(),
"created_at": created_at,
"lat": loc[0],
"lng": loc[1],
}
if doc["type"] == CONTENT_TYPE.ARTICLE:
doc["excerpt"] = titles[random.randrange(0, len(titles) - 1)]
new_content = Article()
else:
new_content = Project()
doc["need_donation"] = True
doc["goal"] = unicode(titles[random.randrange(0, len(titles) - 1)])
if random.randrange(1, 30) == 9:
doc["featured"] = True
print("X", end="")
new_content.save(doc, author)
示例4: post
# 需要导入模块: from models import Article [as 别名]
# 或者: from models.Article import save [as 别名]
def post(self, request, *args, **kwargs):
if request.session.get('account_id', None) is None:
return HttpResponseRedirect('/account/login')
try:
article_id = kwargs['id']
d = request.POST.dict()
i = Article.objects.get(id=article_id)
tag = d.get('tag', '')
if tag != '':
if tag[-1] == ';':
tag = tag[:-1]
i.tag = tag.split(';')
i.category = int(d['category'])
i.head_image = d.get('head_image', None)
i.title = d['title']
i.content = d['content']
i.status = 0
i.save()
except:
d = request.POST.dict()
i = Article(**d)
account_id = request.session['account_id']
i.account_id = str(account_id)
i.username = request.session['username']
tag = d.get('tag', None)
if tag != '':
if tag[-1] == ';':
tag = tag[:-1]
i.tag = tag.split(';')
i.status = 0
i.save()
return HttpResponse(i.id)
示例5: post_article
# 需要导入模块: from models import Article [as 别名]
# 或者: from models.Article import save [as 别名]
def post_article(request,
success_url = "/",
template="articles/post.html"):
""" Post new article """
if request.method == 'POST':
form = ArticleForm(request.POST)
if form.is_valid():
title = form.cleaned_data['title']
content = form.cleaned_data['content']
tags = form.cleaned_data['tags']
# new article
art = Article(title=title,content=content,slug=slugify(title),author=request.user)
art.save()
# add tags
for tag in tags:
try:
t = Tag.objects.get(name=tag)
except Tag.DoesNotExist:
t = None
# if t doesnt exist
if t is None:
t = Tag(name=tag,slug=slugify(tag))
t.save()
# add the tag to the article
art.tags.add(t)
# set meta
art.set_meta()
# done here
return HttpResponseRedirect(success_url)
else:
form = ArticleForm()
return render_to_response(template,
{'form':form},
context_instance=RequestContext(request))
示例6: create_article
# 需要导入模块: from models import Article [as 别名]
# 或者: from models.Article import save [as 别名]
def create_article(request, block_id):
block_id = int(block_id)
block = Block.objects.get(id=block_id)
if request.method == 'GET':
return render_to_response('article_create.html', {'blk': block},
context_instance=RequestContext(request))
else: # request.method == 'POST'
title = request.POST['title'].strip()
content = request.POST['content'].strip()
if not title or not content:
messages.add_message(request, messages.ERROR, u'标题和内容均不能为空')
# 这是Django的消息系统,所有消息都是从后端添加的,这里表示把消息放到用户的请求里面去
return render_to_response('article_create.html',
{'blk': block, 'title': title, 'content': content},
# 如果没有标题或者文章没有内容,这里又把刚才创建文章的页面渲染了一遍,把原来用户填的内容又渲染回去了,
# 在页面上重新把内容填到对应的输入框里,免得用户还要再填一遍。
context_instance=RequestContext(request))
# 这里把用户请求的环境再传到模板中,上面已经传入错误信息的请求就返回给页面了,由页面来控制消息显示
# Django的消息其实是存在数据库里面的,这里传给页面后页面如果不展示,消息会一直保留
# 直到某个页面写了展示消息的代码,这个时候会把所有保留的消息一下展示出来
# owner = User.objects.all()[0]
# 这里因为还没有用户体系,先指定所有文章的作者为管理员
# 井号+空格+TODO空格+事项 有些IDE在你写了这种格式之后都可以调出来一个待办事项列表,TODO后边如果写了什么都会
# 出现在待办事项列表里,每次项目快结题之前都看一下待办事项列表里面的事是不是都做完了
new_article = Article(block=block, owner=request.user, title=title, content=content)
# 这里实例化了一个Article,Article是models.py里定义的数据模型
# block是通过block_id取到的板块,owner是指定的管理员,title和content都是POST传进来的值
new_article.save()
# .save()方法是把这个对象保存,如果是新增对象,对应数据库里的操作就是新增一条记录,
# 如果是通过get方法的到的一个旧有的对象,对应数据库里的就是update操作。
messages.add_message(request, messages.INFO, u'成功发表文章.')
return redirect(reverse('article_list', args=[block.id]))
示例7: new_blog
# 需要导入模块: from models import Article [as 别名]
# 或者: from models.Article import save [as 别名]
def new_blog(request):
if request.method == "POST":
form = BlogForm(request.POST)
if form.is_valid():
_blog = form.save(commit=False)
req_url = BASE_URL % (_blog.name, TEST_API_KEY)
# parse json
req = requests.get(req_url)
jsonlist = json.loads(req.content)
response = jsonlist['response']
posts = response['posts']
blog = response['blog']
# for post in posts:
# print post['body']
_blog.title = blog['title']
_blog.url = blog['url']
_blog.save()
for post in posts:
article = Article()
article.title = post['title']
article.url = post['post_url']
article.description = post['body']
# article.published_date =
# datetime.datetime.fromtimestamp(float(post['timestamp']))
# print article.published_date
article.blog = _blog
article.save()
return redirect('blogs.views.articles_list')
else:
form = BlogForm()
return render(request, "new_blog.html", {"form": form})
示例8: article_save
# 需要导入模块: from models import Article [as 别名]
# 或者: from models.Article import save [as 别名]
def article_save(request):
'''
save article which be sent from article_record page
'''
#import time
#now = time.strftime('%Y-%m-%d %H:%M')
c={}
try:
article = Article(title=request.POST.get('title'),author=request.POST.get('author'),\
content=request.POST.get('content'))
article.save()
c = {
'result':'保存成功!',
'return_code':0,
}
except:
c = {
'result':'Oops!!!好像出了点差错!点书正在努力反省中~~~',
'return_code':1,
}
return render_to_response('article_record/article_save.html',c)
return render_to_response('article_record/article_save.html',c)
示例9: save
# 需要导入模块: from models import Article [as 别名]
# 或者: from models.Article import save [as 别名]
def save(self, username, article=None):
cd = self.cleaned_data
title = cd['title']
title_zh = title
now = datetime.datetime.now()
content_md = cd['content']
content_html = markdown.markdown(cd['content'])
re_title = '<h\d>(.+)</h\d'
data = content_html.split('\n')
for line in data:
title_info = re.findall(re_title, line)
if title_info:
title_zh = title_info[0]
break
url = '/article/%s' % (title)
tags = cd['tags']
article = Article(
url = url,
title = title,
title_zh = title_zh,
author = username,
content_md = content_md,
content_html = content_html,
tags = tags,
views = 0,
created = now,
updated = now,
)
article.save()
示例10: test_reverse_add
# 需要导入模块: from models import Article [as 别名]
# 或者: from models.Article import save [as 别名]
def test_reverse_add(self):
# Adding via the 'other' end of an m2m
a5 = Article(headline='NASA finds intelligent life on Mars')
a5.save()
self.p2.article_set.add(a5)
self.assertQuerysetEqual(self.p2.article_set.all(),
[
'<Article: NASA finds intelligent life on Earth>',
'<Article: NASA finds intelligent life on Mars>',
'<Article: NASA uses Python>',
'<Article: Oxygen-free diet works wonders>',
])
self.assertQuerysetEqual(a5.publications.all(),
['<Publication: Science News>'])
# Adding via the other end using keywords
new_article = self.p2.article_set.create(headline='Carbon-free diet works wonders')
self.assertQuerysetEqual(
self.p2.article_set.all(),
[
'<Article: Carbon-free diet works wonders>',
'<Article: NASA finds intelligent life on Earth>',
'<Article: NASA finds intelligent life on Mars>',
'<Article: NASA uses Python>',
'<Article: Oxygen-free diet works wonders>',
])
a6 = self.p2.article_set.all()[3]
self.assertQuerysetEqual(a6.publications.all(),
[
'<Publication: Highlights for Children>',
'<Publication: Science News>',
'<Publication: Science Weekly>',
'<Publication: The Python Journal>',
])
示例11: test_field_defaults
# 需要导入模块: from models import Article [as 别名]
# 或者: from models.Article import save [as 别名]
def test_field_defaults(self):
a = Article()
now = datetime.now()
a.save()
self.assertTrue(isinstance(a.id, (int, long)))
self.assertEqual(a.headline, "Default headline")
self.assertTrue((now - a.pub_date).seconds < 5)
示例12: loaddir
# 需要导入模块: from models import Article [as 别名]
# 或者: from models.Article import save [as 别名]
def loaddir(directory, clear=False):
if clear:
Article.objects.all().delete()
queue = os.listdir(directory)
urls = set()
while queue:
artfile = queue.pop()
if artfile[0] == '.': continue
if artfile in ('template', 'template.rst', 'template.txt'): continue
artfile = path.join(directory, artfile)
if path.isdir(artfile):
queue.extend([
path.join(artfile,f) for f in os.listdir(artfile)
])
continue
input = file(artfile)
header = {}
linenr = 0
while True:
line = input.readline().strip()
linenr += 1
if line in ('---', '..'): break
if line.find(':') < 0:
raise IOError('gitcms.pages.load: In file %s, line %s. No \':\' found!' % (artfile, linenr))
tag,value = line.split(':',1)
value = value.strip()
header[tag] = value
blank = input.readline()
linenr += 1
if blank.strip():
raise IOError, 'Blank line expected while processing file (%s:%s)\nGot "%s"' % (artfile, linenr,blank)
content = input.read()
content = preprocess_rst_content(content)
url = header['url']
if url and url[-1] == '/':
import warning
warning.warn('''\
gitcms.pages.loaddir: Removing / at end of url (%s)
(Both versions will work for accessing the page.)
''' % url)
url = url[:-1]
if url in urls:
raise IOError('gitcms.pages.loaddir: repeated URL detected (%s)' % url)
taglist = []
for c in header.get('categories','').split():
taglist.append(tag_for(c))
# if we got so far, implies that our article is safe to store.
urls.add(url)
A = Article(title=header['title'], url=url, author=header.get('author', ''), content=content)
A.save()
for c in taglist:
A.tags.add(c)
示例13: newarticle
# 需要导入模块: from models import Article [as 别名]
# 或者: from models.Article import save [as 别名]
def newarticle(request):
if not request.user.is_authenticated():
return redirect('/Login/?next=%s' % request.path)
if request.method=='POST':
title=request.POST['title']
tags=request.POST['tag']
cat=request.POST['cat']
content=request.POST['content']
tags=tags.split(',')
tagm=[]
print tags
for i in tags:
a=Tag.objects.filter(tag=i)
if a:
tagm.append(a[0])
else:
t=Tag(tag=i)
t.save()
tagm.append(t)
if cat.find('mc')>0:
maincat=MainCat.objects.get(id=cat[:cat.find('m')])
ar=Article(user=request.user,title=title,content=content,maincat=maincat)
elif cat.find('-')==-1:
dcat=DetailCat.objects.get(id=cat)
maincat=dcat.maincat
ar=Article(user=request.user,title=title,content=content,detailcat=dcat,maincat=maincat)
else:
ar=Article(user=request.user,title=title,content=content)
ar.save()
ar.tag=tagm
ar.save()
return redirect(getarticle,ar.id)
maincat=MainCat.objects.all()
nart,cart,rart,cm,tg=getthree()
#日历
today=today=datetime.datetime.now()
s=calendar.HTMLCalendar(6)
cals=list(s.itermonthdays2(today.year,today.month))
tdarts=Article.objects.values('id','createtime').filter(createtime__year=today.year,createtime__month=today.month).order_by('createtime') #列表字典[{'createtime': datetime.datetime(2014, 4, 6, 4, 36, 32, 896000, tzinfo=<UTC>)},
tdart=set([i['createtime'].day for i in tdarts])
tmpq=Article.objects.exclude(createtime__year=today.year,createtime__month=today.month)
premon=tmpq.filter(createtime__lt=today).order_by('-createtime')[:1]
aftmon=tmpq.filter(createtime__gt=today).order_by('createtime')[:1]
tt=[]
for i in cals:
tt.append(list(i))
ttt=[]
for a in tt:
for i in tdart:
if a[0] == i:
a.append(1)
if len(a)==2:
a.append(0)
ttt.append(a)
return render_to_response('new.htm',locals(),context_instance=RequestContext(request))
示例14: test_unicode_data
# 需要导入模块: from models import Article [as 别名]
# 或者: from models.Article import save [as 别名]
def test_unicode_data(self):
# Unicode data works, too.
a = Article(
headline=u'\u6797\u539f \u3081\u3050\u307f',
pub_date=datetime(2005, 7, 28),
)
a.save()
self.assertEqual(Article.objects.get(pk=a.id).headline,
u'\u6797\u539f \u3081\u3050\u307f')
示例15: test_microsecond_precision
# 需要导入模块: from models import Article [as 别名]
# 或者: from models.Article import save [as 别名]
def test_microsecond_precision(self):
# In PostgreSQL, microsecond-level precision is available.
a9 = Article(
headline='Article 9',
pub_date=datetime(2005, 7, 31, 12, 30, 45, 180),
)
a9.save()
self.assertEqual(Article.objects.get(pk=a9.pk).pub_date,
datetime(2005, 7, 31, 12, 30, 45, 180))