• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python models.Post类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中models.Post的典型用法代码示例。如果您正苦于以下问题:Python Post类的具体用法?Python Post怎么用?Python Post使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



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

示例1: single_post

def single_post(post_id):
    """Returns everything in a post as json"""
    post_d = mongo.db.posts.find_one(post_id)
    if post_d is None:
        abort(404)
    post = Post(bson=post_d)
    return jsonify(**post.to_dict())
开发者ID:amontalenti,项目名称:muckhacker,代码行数:7,代码来源:api.py


示例2: add_post

def add_post(request):
    if request.method == "POST":
        post_form = PostForm(request.POST, request.FILES)
        if post_form.is_valid():
            title = post_form.cleaned_data['title']
            keywords = post_form.cleaned_data['keywords']
            description = post_form.cleaned_data['description']
            image = post_form.cleaned_data['image']
            text = post_form.cleaned_data['text']
            slug = title

            new_post = Post(title=title,
                                userid=request.user,
                                slug=slug,
                                keywords=keywords,
                                image=image,
                                text=text,
                                description=description,
                                date=datetime.now())
            new_post.save()
            post_form = PostForm()
            return render(request,
                              'blog/add_post.html',
                              {'post_form': post_form})

    else:
        post_form = PostForm()
    ctx = {'post_form': post_form}
    return render(request,
                  'blog/add_post.html',
                  ctx, )
开发者ID:gokhanciplak,项目名称:deneme,代码行数:31,代码来源:views.py


示例3: sub_post

def sub_post(request, id_num): #for nested posts
    pform = PostForm(request.POST or None)
    parent = get_object_or_404(Post, pk=id_num)
    if (request.method == 'POST'
        and request.user.is_authenticated()):
        if pform.is_valid():
            title = pform.cleaned_data["title"]
            check = Post.objects.filter(title=title).order_by("-identifier")
            check_int = 0
            if len(check) > 0:
                check_int = check[0].identifier + 1
            post = Post(title=title,
                        body=pform.cleaned_data["body"],
                        parent=parent,
                        user=request.user,
                        identifier=check_int)
            post.save()
            messages.success(request, "Post submitted correctly")
        else:
        ### meaningful errors here would be helpful
        ### messages.error(request, pform.errors)
            return render_to_response("post_form.html",
                    {'pform' : pform, 'post':parent},
                    RequestContext(request))
    return HttpResponseRedirect("/posts/"+id_num)
开发者ID:NSkelsey,项目名称:cvf,代码行数:25,代码来源:views.py


示例4: test_get_nozomi_dialgs

    def test_get_nozomi_dialgs(self):
        d = feedparser.parse('tests/data/feed.xml')
        entry_elem = d.entries[0]

        post = Post(entry_elem)
        self.assertMultiLineEqual(post.get_nozomi_dialogs()[0],
            u'「原種・亜種と同じく飛び回ったり走り回ったりして追うのが大変なのに、希少種ときたら頭も硬いのが厄介ですよね」')
开发者ID:so-c,项目名称:nozomi_miraha,代码行数:7,代码来源:test_post.py


示例5: test_parse_post

    def test_parse_post(self):
        response = '''{"comments": {"can_post": 0, "count": 4},
                 "date": 1298365200,
                 "from_id": 55555,
                 "geo": {"coordinates": "55.6745689498 37.8724562529",
                  "place": {"city": "Moskovskaya oblast",
                   "country": "Russian Federation",
                   "title": "Shosseynaya ulitsa, Moskovskaya oblast"},
                  "type": "point"},
                 "id": 465,
                 "likes": {"can_like": 1, "can_publish": 1, "count": 10, "user_likes": 0},
                 "online": 1,
                 "post_source": {"type": "api"},
                 "reply_count": 0,
                 "reposts": {"count": 3, "user_reposted": 0},
                 "text": "qwerty",
                 "to_id": 201164356}
            '''
        instance = Post()
        owner = UserFactory(remote_id=201164356)  # Travis Djangov
        author = UserFactory(remote_id=55555)
        instance.parse(json.loads(response))
        instance.save()

        self.assertTrue(instance.remote_id.startswith('201164356_'))
        self.assertEqual(instance.wall_owner, owner)
        self.assertEqual(instance.author, author)
        self.assertEqual(instance.reply_count, 0)
        self.assertEqual(instance.likes, 10)
        self.assertEqual(instance.reposts, 3)
        self.assertEqual(instance.comments, 4)
        self.assertEqual(instance.text, 'qwerty')
        self.assertTrue(isinstance(instance.date, datetime))
开发者ID:Core2Duo,项目名称:django-vkontakte-wall,代码行数:33,代码来源:tests.py


示例6: get

  def get(self):
    page = helper.sanitizeHtml(self.request.get('pagina'))
    perPage = 20
    page = int(page) if page else 1
    realPage = page - 1
    if realPage > 0:
      prevPage = realPage
    if (page * perPage) < Post.get_cached_count():
      nextPage = page + 1

    session = get_current_session()
    if session.has_key('user'):
      user = session['user']
    posts = Post.all().order('-created').fetch(perPage,perPage * realPage)
    prefetch.prefetch_posts_list(posts)
    i = perPage * realPage + 1
    for post in posts:
      post.number = i
      i = i + 1
    if helper.is_json(self.request.url):
      posts_json = [p.to_json() for p in posts]
      if(self.request.get('callback')):
        self.response.headers['Content-Type'] = "application/javascript"
        self.response.out.write(self.request.get('callback')+'('+simplejson.dumps({'posts':posts_json})+');')
      else:
        self.response.headers['Content-Type'] = "application/json"
        self.response.out.write(simplejson.dumps({'posts':posts_json}))
    else:
      self.response.out.write(template.render('templates/main.html', locals()))
开发者ID:mantus,项目名称:Noticias-HAcker,代码行数:29,代码来源:main.py


示例7: profile

def profile(): 

	form = CreatePostForm()		
	# session gets the encrypted ID and hashes it to get the value i.e. the username
	user = User.query.filter_by(username = session['username']).first()

	if user is None:
		return redirect(url_for('signin'))
	else:
		if request.method == 'POST':						
			if form.validate() == False:				
				return render_template('profile.html', form=form,communityform=CreateCommunityForm())
			else:				
				newpost = Post(form.text.data, session['userID'], form.categoryID)				
				db.session.add(newpost)
				
				file = request.files[form.image.name]				
				if file: 					
					filename = secure_filename(file.filename)
					# flush to ge the postID to be used as filename
					db.session.flush()				
					filename = str(newpost.postID) + os.path.splitext(filename)[1]
					newpost.imageURI = filename
					file.save(os.path.join(APP_UPLOADS, filename))								
					flash(filename+" uploaded!")		
										
					
				db.session.commit()
				
				flash("posted!")			
				return redirect(url_for('profile'))
		elif request.method == 'GET':		
			# posts = Post.query.filter_by(username = session['username']).first()
			return render_template('profile.html', form=form, communityform=CreateCommunityForm())
开发者ID:akarki15,项目名称:reddit-images,代码行数:34,代码来源:routes.py


示例8: show_page

def show_page(num):
    p = Page(num, per_page, Post.find().count())
    p.urlfunc = lambda num: url_for("blog.show_page", num=num)
    if not p.exists:
        abort(404)
    posts = Post.find({"is_published": True}).order_by("-timestamp")[p.slice()]
    return render_template("blog/index.html", posts=posts, page=p)
开发者ID:jmoiron,项目名称:jmoiron.net,代码行数:7,代码来源:views.py


示例9: edit_or_create_post

def edit_or_create_post(request):
    try:
        user = TestProfile.objects.get(email=request.user.email)
        post = Post.objects.get(user=user)
        provided, type = json.loads(post.provided), json.loads(post.house_type)
    except Post.DoesNotExist:
        post = None
        type = None
        provided = None
    except TestProfile.DoesNotExist:
        user = None

    if request.POST.get('add'):
        if user is not None and post is None:
            user.num_posts += 1
            post = Post(user=user, region=user.region, sub_region='Berkeley', distance='',
                        title=request.POST.get('title'),
                        house_type=json.dumps(request.POST.getlist('housing_type[]')),
                        provided=json.dumps(request.POST.getlist('provided[]')),
                        proximity='10 minute walk',
                        num_people=1,
                        notes=request.POST.get('notes'))
            post.save()
            provided, type = json.loads(post.provided), json.loads(post.house_type)
            print(provided)
    elif request.POST.get('delete'):
        if user.num_posts > 0:
            user.num_posts -= 1
        if post is not None:
            post.delete()
    user.save()
    context = {'user': user, 'post': post, 'type': type, 'provided': provided}
    return render(request, 'temporary_housing/edit_or_create_post.html', context)
开发者ID:mitchkarns,项目名称:bnb,代码行数:33,代码来源:views.py


示例10: get_context_data

    def get_context_data(self, *args, **kwargs):

        ctx = super(PostList, self).get_context_data(*args, **kwargs)

        page = self.request.GET.get('p', 1)

        if self.request.user.is_authenticated():
            objects = Post.all().order("-post_date")
        else:
            objects = Post.published().order("-post_date")


        pager = Paginator(objects, PAGE_SIZE)

        try:
            page_obj = pager.page(page)
        except InvalidPageException:
            raise Http404

        ctx.update({
            'paginator': pager,
            'page_obj': page_obj,
        })

        return ctx
开发者ID:sleepyjames,项目名称:sleepyjames-aeblog,代码行数:25,代码来源:views.py


示例11: fetch

def fetch(request):
    if request.method != 'GET':
        raise Http404

    params = {}
    for k in ('since_id', 'until_id', 'count'):
        if k in request.GET:
            params[k] = request.GET[k]

    since_post = None
    until_post = None 
    if 'since_id' in params:
        since_post = Post.get_by_id(int(params['since_id']))

    elif 'until_id' in params:
        until_post = Post.get_by_id(int(params['until_id']))

    count = 8
    if 'count' in params and re.match('\d+', params['count']):
        count = int(params['count'])
        if not (count >= 1 and count <= 8):
            count = 8
        
    posts = Post.fetch(**{
        'since_post' : since_post, 
        'until_post' : until_post,
        'count' : count
    })
    
    return util.respond(True, [post.to_dict() for post in posts])
开发者ID:jeloou,项目名称:potatopoteito,代码行数:30,代码来源:views.py


示例12: publications

def publications(request):
    if request.method == 'POST':
       # save new post
       title = request.POST['title']
       authors = request.POST['authors']
       publisher = request.POST['publisher']
       papertype = request.POST['papertype']
       page_num = request.POST['page_num']
       additional_info = request.POST['additional_info']
#       selectedpublication = request.POST['selectedpublication']
       str_date_published = request.POST['date_published']

       post = Post(title=title)
#       post.date_published = datetime.datetime.now() 
       post.date_published = datetime.fromtimestamp(mktime(time.strptime(str_date_published, "%b %d %Y")))
       post.authors = authors
       post.papertype = papertype
       post.page_num = page_num
       post.additional_info = additional_info
       post.publisher = publisher
       if request.POST.get('selectedpublication', True):
           post.selectedpublication = True;
       post.save()

    # Get all posts from DB
    posts = Post.objects

    return render_to_response('admin/publications.html', {'Posts': posts},
                              context_instance=RequestContext(request))                              
开发者ID:micadeyeye,项目名称:Blongo,代码行数:29,代码来源:views.py


示例13: test_comment_approved

 def test_comment_approved(self):
     post = Post(author=self.me, title="Hi", created_date=timezone.now())
     post.save()
     comment = Comment(author=self.me.username, post=post)
     comment.approve()
     comment.save()
     assert comment in post.approved_comments()
开发者ID:bananayana,项目名称:blog-igi,代码行数:7,代码来源:tests.py


示例14: post

    def post(self, request):
        """
        Crea un post a partir de la información POST
        """
        success_message = ''
        post_with_owner = Post()
        post_with_owner.owner = request.user # aquí asignamos al usuario como propietario del post
        form = PostForm(request.POST, instance=post_with_owner)

        if form.is_valid():

            new_post = form.save()
            form = PostForm() # reiniciamos el form
            success_message = 'Post almacenado con éxito! '
            success_message += '<a href="{0}">'.format(
                reverse('post_detail', args=[request.user.username, new_post.pk])
            )
            success_message += 'Ver post'
            success_message += '</a>'

            context = {
                'form': form,
                'success_message': success_message
            }
            return render(request, 'blogs/new_post.html', context)
开发者ID:TimpleSoft,项目名称:Wordplease,代码行数:25,代码来源:views.py


示例15: feed_update

def feed_update(id=None):

    # Manual update of one or all feeds now
    if request.json['action'] == 'refresh':
        
        # Call refresh routine
        # TODO: RSS worker functions in separate package
        # TODO: Need to capture return status
        if id is None:
            rss_spawn() # Update all feeds
        else:
            try:
                feed = Feed.get(Feed.id == id)
            except Feed.DoesNotExist:
                return jsonify(**FEED_NOT_FOUND)

            rss_worker(feed) # Update single feed
        
        # return JSON status OK
        return jsonify(**STATUS_OK)

    # Mark one or all feeds read
    elif request.json['action'] == 'markread':

        if id is None:
            # Mark all posts read
            query = Post.update(is_read=True)
        else:
            # Mark posts in current feed read
            query = Post.update(is_read=True).where(Feed.id == id)
            
        query.execute()
            
    # return JSON status OK
        return jsonify(**STATUS_OK)
开发者ID:KyubiSystems,项目名称:Wisewolf,代码行数:35,代码来源:views.py


示例16: show_all_posts

def show_all_posts():
    """the homepage of the site where all the posts will be shown in a table"""
    show_followed = False
    # get the variable "show-all" from the template to determine whether to show all posts or followed ones
    show_what = request.args.get('show-all')
    page = request.args.get('page', 1, type=int)
    print show_what, "this is show_what"
    if show_what == "false":
        show_followed = True

    if show_followed:
        viewer_id = session.get('loggedin', None)
        viewer = User.get_user_by_id(viewer_id)
        posts_all = viewer.followed_posts()
        pagination = viewer.followed_posts_pagination(page)
    else:
        posts_all = Post.get_all_posts()
        pagination = Post.get_all_posts_pagination(page)
    if posts_all:
        session["post_ids"] = [post.post_id for post in posts_all]
    tags = Tag.sort_all_tags_by_popularity()

    posts = pagination.items  # the records in the current page

    return render_template('post_list.html', posts=posts, tags=tags, pagination=pagination)
开发者ID:PeggyZheng,项目名称:Opinionated,代码行数:25,代码来源:server.py


示例17: delete

def delete(user, id):
	post = Post.find_by_id(id)
	if post:
		Post.delete(user,id)
		return redirect('/home')
	else:
		abort(404)
开发者ID:kevinmangan,项目名称:Tweeter,代码行数:7,代码来源:routes.py


示例18: save

 def save(self):
     topic_post = False
     if not self.topic:
         topic_type = self.cleaned_data["topic_type"]
         if topic_type:
             topic_type = TopicType.objects.get(id=topic_type)
         else:
             topic_type = None
         topic = Topic(
             forum=self.forum,
             posted_by=self.user,
             subject=self.cleaned_data["subject"],
             need_replay=self.cleaned_data["need_replay"],
             need_reply_attachments=self.cleaned_data["need_reply_attachments"],
             topic_type=topic_type,
         )
         topic_post = True
         topic.save()
     else:
         topic = self.topic
     post = Post(
         topic=topic,
         posted_by=self.user,
         poster_ip=self.ip,
         message=self.cleaned_data["message"],
         topic_post=topic_post,
     )
     post.save()
     if topic_post:
         topic.post = post
         topic.save()
     attachments = self.cleaned_data["attachments"]
     post.update_attachments(attachments)
     return post
开发者ID:alexliyu,项目名称:mobilesystem,代码行数:34,代码来源:forms.py


示例19: view

def view():
    from models import User, Post

    if request.method == 'POST':

        form = AddPostForm(request.form)
        if form.validate():

            post = Post(title=form.data['title'], content=form.data['content'], user=current_user)
            post.is_visible = True

            print("{} is creating a new {}'th post!".format(
               post.user.username, len(post.user.posts.all()) + 1))
            print post.id

            db.session.add(post)
            db.session.commit()
            flash('Post created!')

        else:
            flash('Form is not valid! Post was not created.')

    else:
        form = AddPostForm()

    posts = Post.query.filter_by(is_visible=True).all()
    return render_template('home.html', form=form, posts=posts)
开发者ID:andyzt,项目名称:tceh,代码行数:27,代码来源:views.py


示例20: publish

def publish(user_id):
    form = PublishBlogForm()
    posts = Post()
    if form.validate_on_submit():
        blog_body = request.form.get("body")
        if not len(strip(blog_body)):
            flash("The content is necessray!")
            return redirect(url_for("publish", user_id=user_id))
        posts.body = blog_body
        posts.timestamp = datetime.datetime.now()
        posts.user_id = user_id

        try:
            db.session.add(posts)
            db.session.commit()
        except:
            flash("Database error!")
            return redirect(url_for("publish", user_id=user_id))

        flash("Publish Successful!", "success")
        return redirect(url_for("publish", user_id=user_id))

    return render_template(
        "publish.html",
        form=form)
开发者ID:yaoice,项目名称:flask-micblog,代码行数:25,代码来源:views.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python models.Product类代码示例发布时间:2022-05-27
下一篇:
Python models.Playlist类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap