当前位置: 首页>>代码示例>>Python>>正文


Python Blog.save方法代码示例

本文整理汇总了Python中blog.models.Blog.save方法的典型用法代码示例。如果您正苦于以下问题:Python Blog.save方法的具体用法?Python Blog.save怎么用?Python Blog.save使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在blog.models.Blog的用法示例。


在下文中一共展示了Blog.save方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: add_blog

# 需要导入模块: from blog.models import Blog [as 别名]
# 或者: from blog.models.Blog import save [as 别名]
def add_blog(request):
	try:
		req = convertRequest(request)

	 	category_name = req.get('category_name', '')
	 	if category_name != '':
	 		category_name = req.get('category_name', '')
	 		category = Category.objects.get_or_create(category_name=category_name)[0]
			category_id = category.id
		else:
			category_id = req.get('category_id', 0)

		title = req.get('title', '')
		content =req.get('content', '')
		user_id = req.get('user_id', 0)

		if title != '' and category_id != 0 and user_id != 0:
			user = User.objects.get(id=user_id)
			category = Category.objects.get(id=category_id)
			blog = Blog(title=title, content=content, category=category, user=user)
			blog.save()
			return HttpResponse(response_json.success())

	except Exception, e:
		return HttpResponse(response_json.fail(traceback.format_exc()))
开发者ID:azhugg,项目名称:VBlog,代码行数:27,代码来源:views.py

示例2: make_blog

# 需要导入模块: from blog.models import Blog [as 别名]
# 或者: from blog.models.Blog import save [as 别名]
def make_blog(sender, **kwargs):
    """
    Create a new blog during syncdb. The user
    *should* create a superuser so assume that
    this is the blog author.
    """
    if not kwargs['interactive']:
        return

    # Do nothing if a blog already exists
    try:
        blog = Blog.objects.all()[0]
        return
    except IndexError:
        pass

    # Create a blog if a user exists
    try:
        author = User.objects.all()[0]
    except IndexError:
        return

    try:
        # Prompt for a blog title
        title = raw_input('Blog title: ')
        blog = Blog(title=title, author=author)
        blog.save()
    except KeyboardInterrupt:
        sys.stderr.write("\nOperation cancelled.\n")
        sys.exit(1)
开发者ID:danielnaab,项目名称:mightylemon,代码行数:32,代码来源:management.py

示例3: process_item

# 需要导入模块: from blog.models import Blog [as 别名]
# 或者: from blog.models.Blog import save [as 别名]
    def process_item(self, item, spider):
        blog=Blog()
        blog.blog_title=item['title']
        #blog.blog_text="[%s](%s)"%(item['title'],item['href'])
        #处理href,只取最后几位数字
        num=item['href'].split('.')[-2][-7:]
        blog.blog_text='blog/html/'+num+'.html'
        blog.blog_img=''
        blog.blog_text_brief=''
        blog.pub_date=datetime.datetime.strptime(item['date_str'],'%Y-%m-%d %H:%M')
        blog.blog_praise=int(item['commentnum'])
        blog.save()
        
     
        #html=open(blog.blog_text,'w')
        #content=item['content']
        #html.write(content.encode("gbk"))
        #html.close()
        html_dir='/home/dk/mysite/blog/templates/'+blog.blog_text

        file=open(html_dir,'w')

        u=item['content']
        
        file.write(u.encode('utf-8'))#utf8转str
        
        file.close()
        
        
        
        return item
开发者ID:haireggs,项目名称:crawler,代码行数:33,代码来源:pipelines.py

示例4: add_news

# 需要导入模块: from blog.models import Blog [as 别名]
# 或者: from blog.models.Blog import save [as 别名]
def add_news(request):

    if not request.user.is_authenticated():
        
        return redirect('/login/')
    else:
        error = ""
        title = content = ""
        maybe_title=maybe_content=""

        if 'add_title' in request.POST and 'add_content' in request.POST: 
            add_title = request.POST.get('add_title')
            add_content = request.POST.get('add_content')
            if not add_content or not add_title:
                error = "please enter the form completely"
                maybe_title = request.POST.get('add_title')
                maybe_content = request.POST.get('add_content')
            else:
                #print 'time'
                #print datetime.datetime.now()
                p = Blog(title=add_title,content = add_content,time=datetime.datetime.now())
                p.save()
                return redirect('/cpanel/')

    return render(request, 'addnews.html', {'state':error,'maybe_title':maybe_title,'maybe_content':maybe_content})
开发者ID:theSinner,项目名称:newblog,代码行数:27,代码来源:views.py

示例5: create_sample

# 需要导入模块: from blog.models import Blog [as 别名]
# 或者: from blog.models.Blog import save [as 别名]
def create_sample(num_blogs=50,
                  num_posts_per_blog=4,
                  num_comments_per_post=7,
                  ):
    for name in names:
        User.objects.create_user(name, '%[email protected]' % name, '')
    users = list(User.objects.all())
    for i in range(0, num_blogs):
        blog = Blog()
        blog.submitter = random.choice(users)
        blog.name = random.choice(text.split())
        blog.save()
    for blog in Blog.objects.all():
        blog.submitter = random.choice(users)
        blog.save()
        for i in range(0, num_posts_per_blog):
            post = Post.objects.create(body=text,
                                       blog=blog,
                                       name=random.choice(text.split()),
                                       )
            for u in users:
                if random.choice(range(0, 6)) == 0:
                    post.likers.add(u)
    for post in Post.objects.all():
        for i in range(0, num_comments_per_post):
            PostComment.objects.create(submitter=random.choice(users),
                                       post=post,
                                       body=text,
                                       )
开发者ID:adamsc64,项目名称:a-related-matter,代码行数:31,代码来源:tests.py

示例6: create_blog

# 需要导入模块: from blog.models import Blog [as 别名]
# 或者: from blog.models.Blog import save [as 别名]
def create_blog(request):
	errors = []
	template = "blog/templates/create_blog.html"
	form = CreateBlogForm()
	user = request.user

	if not user.is_authenticated():
		raise Http404

	if request.method == "POST":
		form = CreateBlogForm(request.POST)

		if form.is_valid():
			try:
				data = form.cleaned_data
				_blog = Blog()
				_blog.title = data["title"]
				_blog.owner = user
				_blog.url = data["url"]
				_blog.tagline = data["tagline"]
				_blog.active = True
				_blog.save()
				_blog.contributors.add(user)
				_blog.save()
				return HttpResponseRedirect("/blog/%s/"%user.username)
			except:
				errors.append("Blog URL already taken.")

	return render(request, template, {"errors":errors, "form":form})
开发者ID:ravimalik20,项目名称:blogApp,代码行数:31,代码来源:views.py

示例7: newblog

# 需要导入模块: from blog.models import Blog [as 别名]
# 或者: from blog.models.Blog import save [as 别名]
def newblog (request, page_id):
    u = User.objects.get (id=get_uid ())
    
    if is_prepare ():
        blog_ls = base_ls ()
        blog_ls.set_S (flmo.Label (set (blog_ls.get_S ()) | set (prepare_stags ())))
        bp = make_blogpointer (base_ls (), u, blog_ls, page_id)
        return ("Created BlogPointer with id %d and S label %s for page_id %s"
                % (ap.id, blog_ls, page_id))

    elif request.POST.has_key ('title'):
        title = request.POST['title']
        previous_page_id = request.POST['page_id']
        try:
            bp = BlogPointer.objects.get (page_id=previous_page_id)
        except BlogPointer.DoesNotExist:
            bp = make_blogpointer (base_ls (), u, base_ls (), page_id)

        b = Blog (blogpointer=bp, title=title, owner=u, pub_date=datetime.datetime.now ())
        b.save (desls=bp.get_labelset ())
        return HttpResponseRedirect (urlprefix () + '/upload/newpost/%d/%d/' % (b.id, new_page_id ()))

    else:
        return render_to_response ('newblog.html',
                                   {'urlprefix': urlprefix (),
                                    'page_id': page_id,
                                    'new_page_id': new_page_id (),
                                    })
开发者ID:imosts,项目名称:flume,代码行数:30,代码来源:views.py

示例8: make

# 需要导入模块: from blog.models import Blog [as 别名]
# 或者: from blog.models.Blog import save [as 别名]
    def make(self, **kwargs):
        make_path = kwargs.get("make", "")
        if not make_path:
            smart_print(u"请指定文件名")

        post_root = settings.POST_DIR_ROOT
        path = os.path.join(post_root, "%s.md" %make_path)
        file_handler = open(path, "r")
        text = file_handler.read()
        file_handler.close()

        html = md.convert(text.decode("utf-8"))
        metadata = parse_meta(md)
        metadata['content'] = HtmlFormatter.format_html(html)
        title = metadata.get("title", "")
        if not title:
            print("MD文件无title")
            return

        blog = Blog.get_by_unique(title=title)
        if not blog:
            blog = Blog()

        for key, value in metadata.items():
            setattr(blog, key, value)

        blog.save()
        smart_print("博客: %s,存储成功" %title)
开发者ID:chenchiyuan,项目名称:blog,代码行数:30,代码来源:posts.py

示例9: blog_add

# 需要导入模块: from blog.models import Blog [as 别名]
# 或者: from blog.models.Blog import save [as 别名]
def blog_add(request):
    if request.method == 'POST':
        form = BlogForm(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']
            for taglist in tagname.split():
                Tag.objects.get_or_create(tag_name=taglist.strip())
                title = cd['caption']
                author = Author.objects.get(id=1)
                content = cd['content']
                blog = Blog(caption=title, author=author,
                            content=content)
                blog.save()
            for taglist in tagname.split():
                blog.tags.add(Tag.objects.get(tag_name=taglist.strip()))
                blog.save()
            id = Blog.objects.order_by('-publish_time')[0].id
            return HttpResponseRedirect('/myblog/blog/%s' % id)
        #return HttpResponseRedirect(reverse('detailblog',args=[id]))
    else:
        form = BlogForm()
        tag = TagForm(initial={'tag_name': 'notags'})
    return render(request,'blog_add.html', {'form': form, 'tag': tag},
                         context_instance=RequestContext(request))
开发者ID:zongshizhen,项目名称:myblog,代码行数:29,代码来源:views.py

示例10: newPost

# 需要导入模块: from blog.models import Blog [as 别名]
# 或者: from blog.models.Blog import save [as 别名]
    def newPost(self, blogid, username, password, struct, publish):
        self.__isUser(username, password)
        # print(("blogid:", blogid))
        # print(("struct:", struct))

        title = struct['title']
        content = struct['description']
        categorie = struct['categories'][0]

        #生成静态HTML文件
        id = None
        try:
            path = r'{0}/templates'.format(os.path.dirname(__file__))
            id = len(sum([i[2] for i in os.walk(path)], []))
            # print("博客ID:", id)
            static(id, content, categorie, title)

            blog = Blog()
            blog.blog_id = id
            blog.title = title
            blog.categorie = categorie
            blog.content = content
            blog.summary = get_summary(content, 150, u'...')
            blog.post_time = datetime.datetime.today()
            blog.save()

        except Exception as e:
            error_log.error("生成静态文件失败:{0}".format(e))

        return id
开发者ID:mazhenpy,项目名称:pylabsite,代码行数:32,代码来源:views.py

示例11: post

# 需要导入模块: from blog.models import Blog [as 别名]
# 或者: from blog.models.Blog import save [as 别名]
    def post(self, request):
        """
        Crea un user en base a la información POST
        :param request: HttpRequest
        :return: HttpResponse
        """
        success_message = ''

        form = SignupForm(request.POST)
        if form.is_valid():
            user = User()
            user.username = form.cleaned_data.get('usr')
            user.first_name = form.cleaned_data.get('first_name')
            user.last_name = form.cleaned_data.get('last_name')
            user.email = form.cleaned_data.get('email')
            user.set_password(form.cleaned_data.get('password'))
            user.save()

            blog = Blog()
            blog.title = "My first blog"
            blog.owner = user
            blog.save()

            success_message = 'Creado con éxito!'
            success_message += '<a href="{0}">'.format(
                reverse('post_home', args=[])
            )
            success_message += 'go Home!'
            success_message += '</a>'
        context = {
            'form': form,
            'success_message': success_message
        }
        return render(request, 'users/new_user.html', context)
开发者ID:AgDP,项目名称:Django-Wordplease,代码行数:36,代码来源:views.py

示例12: to_mysql

# 需要导入模块: from blog.models import Blog [as 别名]
# 或者: from blog.models.Blog import save [as 别名]
def to_mysql(req):
    path = r'{0}/templates'.format(os.path.dirname(__file__))
    num = len(sum([i[2] for i in os.walk(path)], [])) - 1
    id = 1
    for i in range(num):
        url = "{0}/templates/{1}.html".format(os.path.dirname(__file__), id)
        #url = "blog/templates/1.html"
        try:
            soup = BeautifulSoup(open(url, encoding="UTF-8"))
            if len(soup):
                categorie = soup.find(id='categorie').string
                blog_id = id
                title = soup.find(id='blog_title').string
                post_time = str(soup.find(id='blog_post_time'))[35:45]

                blog = Blog()
                blog.blog_id = blog_id
                blog.title = title
                blog.post_time = post_time
                blog.categorie = categorie
                blog.save()
            else:
                break
        except Exception as e:
            error_log.error(e)
        finally:
            id += 1
    return HttpResponse("<div style='text-align:center;'>{0} - To-Mysql-Done</div>".format(id))
开发者ID:mazhenpy,项目名称:pylabsite,代码行数:30,代码来源:views.py

示例13: editor

# 需要导入模块: from blog.models import Blog [as 别名]
# 或者: from blog.models.Blog import save [as 别名]
def editor(request):
	if request.method == 'POST' :
		if 'content' in request.POST:
			blog=Blog(title=request.POST['title'].encode('utf8'),content=request.POST['content'].encode('utf8'))
			blog.save()
	return render_to_response('editor.html', 
		{'title': '编辑日志'
		},context_instance=RequestContext(request))
开发者ID:daihaovigg,项目名称:django,代码行数:10,代码来源:views.py

示例14: createBlog

# 需要导入模块: from blog.models import Blog [as 别名]
# 或者: from blog.models.Blog import save [as 别名]
def createBlog(user):
  
	blog=Blog()
	blog.user_id=user.id
	blog.title=user.username+"的博客".decode("utf-8")
	blog.modules="profile,hotarticlelist,hotcommentlist"
	blog.template="default"
	blog.createtime=datetime.datetime.now()
	blog.save()
开发者ID:xf22001,项目名称:myblog,代码行数:11,代码来源:common.py

示例15: metaWeblog_newPost

# 需要导入模块: from blog.models import Blog [as 别名]
# 或者: from blog.models.Blog import save [as 别名]
def metaWeblog_newPost(user, blogid, struct, publish):
    # todo - parse out technorati tags
    post = Blog(title = struct['title'],
                body_markdown = struct['description'],
                slug = struct.get('permaLink', None),
               )
    post.save()
    setTags(post, struct)
    return post.id
开发者ID:Sanlucifer,项目名称:sun-run-away,代码行数:11,代码来源:metaweblog.py


注:本文中的blog.models.Blog.save方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。