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


Python models.Article类代码示例

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


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

示例1: create_article

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]))
开发者ID:Billin9,项目名称:bbs,代码行数:32,代码来源:views.py

示例2: article_save

def article_save():
    mid = request.form.get('id')
    title = request.form.get('title', '')
    content = request.form.get('content', '')
    
    if (mid == None or mid == ''):
        article = Article(title=title, content=content, add_time=datetime.now(), edit_time=datetime.now())
        for cid in request.form.getlist("tags"):
            article.tags.add(Tag.query.get(cid))
        for cid in request.form.getlist("categories"):
            article.categories.add(Category.query.get(cid))
        db.session.add(article)
    else:
        article = Article.query.get(int(mid))
        article.title=title
        article.content=content
        article.edit_time=datetime.now()
        article.categories.clear()
        article.tags.clear()
        for cid in request.form.getlist("tags"):
            article.tags.add(Tag.query.get(cid))
        for cid in request.form.getlist("categories"):
            article.categories.add(Category.query.get(cid))
            
    db.session.commit()
    flash('保存成功!', 'success')
    return redirect(url_for('.article',page=1))
开发者ID:x20080406,项目名称:theblog,代码行数:27,代码来源:controllers.py

示例3: create

def create():
    if 'email' not in session:
        return redirect(url_for('index'))
    person = Person.query.filter_by(email=session['email']).first()
    if person:
        article = Article()
        print 'Article created'
        form = ArticleCreateForm()
        print 'Form created'
        name = person.firstname
        print 'name assigned'
        form.person_name.data = person.firstname
        if form.validate_on_submit():
            print 'inside article post'
            form.populate_obj(article)
            url = form.url.data
            print url
            if url:
                arch_local = image(url, person.firstname)
                article.arch_local = arch_local
            db.session.add(article)
            db.session.commit()
            return redirect(url_for('index', name=name))
        return render_template('create.html', form=form, person=person, name=name)
    return redirect(url_for('index'))
开发者ID:mauri84,项目名称:blogtest,代码行数:25,代码来源:views.py

示例4: get_article

def get_article(id, user=None):
    """Gets a single article (formatted by json_data) from redis or postgresql
    And performs some pre-filters for the current user
    Args:
        id (int): id
        user (User): the current user
    Returns:
        None if the article is not existed or a dict of article data
    """
    id = int(id)
    key = Article.cache_key(id)
    redis_client = get_client(key)

    article = None
    if not redis_client.exists(key):
        article = Article.find_by_pk(id)
        if article:
            data = article.json_data()
            redis_client.set(key, json.dumps(data))
            article = data
    else:
        if redis_client.type(key) == 'hash':
            print redis_client
        article = json.loads(redis_client.get(key))

    article['user_vote'] = Article.check_vote(user, article['id'])

    return article
开发者ID:laoshanlung,项目名称:flask-demo,代码行数:28,代码来源:article.py

示例5: save

 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()
开发者ID:qiwsir,项目名称:practice,代码行数:29,代码来源:forms.py

示例6: list

def list():
    is_active = request.args.get('is_active', 1);   
    is_active = int(is_active) 
    is_active = is_active == 1

    user = g.user

    if not user:
        is_active = True
    elif user and not user.has_permission('approve_article'):
        is_active = True

    limit = int(request.args.get('limit', 10))
    offset = int(request.args.get('offset', 0))

    order = request.args.get('order', '-date_created')

    if is_active:
        articles = cache.get_articles(user=user, sort_by=order, limit=limit, offset=offset)
    else:
        order_strings = process_order_input(order)
        articles = Article.list(is_active=is_active, limit=limit, offset=offset, order=order_strings, json=True)
    
    pagination = {
        "total": Article.count(),
        "offset": int(offset),
        "limit": int(limit)
    }

    return jsonify(dict(data=articles, pagination=pagination))
开发者ID:laoshanlung,项目名称:flask-demo,代码行数:30,代码来源:api_articles.py

示例7: test_reverse_add

    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>',
            ])
开发者ID:0xmilk,项目名称:appscale,代码行数:34,代码来源:tests.py

示例8: store

    def store(self, topic_name, article_entry_list):
        """Stores the article entries in the database.

        :param topic_name The name of the topic
        :param article_entry_list The list of entries of this topic
        """

        try:
            # Try to retrieve the topic to see if it exists already
            topic = Topic.get(Topic.name == topic_name)
        except Topic.DoesNotExist:
            # If not, create it
            topic = Topic.create(name=topic_name)

        # Go through all the articles in this topic
        for article_entry in article_entry_list:
            article_name = article_entry.subject

            # If there is no subject, it means the article is corrupted
            # therefore we skip it
            if not article_name:
                continue

            # Create the files with the content
            # Overwrite existing files
            try:
                Article.create(topic=topic, subject=article_name,
                               body=article_entry.body)
            except Article.DoesNotExist:
                pass
开发者ID:QFAPP,项目名称:QF,代码行数:30,代码来源:__init__.py

示例9: createArticle

    def createArticle(self, request):
        """Create new Article object, returning ArticleForm/request."""
        
        for required in ['title', 'content']:
            if not getattr(request, required):
                raise endpoints.BadRequestException("Article '%s' field required" % required)

        # copy ArticleForm/ProtoRPC Message into dict
        data = {field.name: getattr(request, field.name) for field in request.all_fields()}

        if data['view'] == None:
            del data['view']
        else:
            data['view'] = str(data['view'])

        author = self._getAuthorFromUser()
        data['authorName'] = author.displayName

        article_id = Article.allocate_ids(size=1, parent=author.key)[0]
        article_key = ndb.Key(Article, article_id, parent=author.key)
        data['key'] = article_key

        # create Article
        article_key = Article(**data).put()

        # send email to author confirming creation of Article
        taskqueue.add(params={'email': author.mainEmail,
            'ArticleInfo': repr(request)},
            url='/tasks/send_confirmation_email'
        )

        return self._copyArticleToForm(article_key.get(), author=author)
开发者ID:dansalmo,项目名称:new-aca,代码行数:32,代码来源:aca.py

示例10: post

    def post(self):
        d = json.loads(self.request.body)
        if d['secret'] == '16jutges16':
            if 'key' in d and len(d['key']) > 10: #Keys are looong.
                article = ndb.Key(urlsafe = d['key']).get()
                logging.info('Modifying entry {}'.format(d['key']))
            else:
                article = Article()

            article.slug     = d['slug']
            article.title    = d['title']
            article.text     = d['text']
            if 'when' in d:
                # Matches isoformat into datetime object. Found in stackoverflow
                article.when = datetime.datetime(
                    *map(int, re.split('[^\d]', d['when'])[:-1])
                )
            else:
                article.when = datetime.datetime.now()

            try:
                article.keywords = string.split(d['keywords'])
            except AttributeError:
                article.keywords = d['keywords']
            
            article.put()
开发者ID:guillemborrell,项目名称:guillemborrell,代码行数:26,代码来源:resources.py

示例11: scrape_homepage

    def scrape_homepage(self, **kwargs):
        """
        Scrape!
        """
        logger.info('Scraping homepage (start time: %s)' % self.run_time)

        if not kwargs:
            response = requests.get(self.url)

            page = PyQuery(response.content)
        else:
            page = PyQuery(**kwargs)

        article_elements = page('.stories-wrap article')
        slot = 0
        articles = []

        for el in article_elements:
            element = PyQuery(el)

            article = Article(element, self.run_time)

            if not article.story_id and not article.is_apps_project:
                continue

            if not element.hasClass('attachment'):
                slot += 1

            article.slot = slot
            articles.append(article)
            logger.info('Scraped %s from homepage (%s)' % (article.story_id, article.headline))

        return articles
开发者ID:ebigalee,项目名称:graeae,代码行数:33,代码来源:scraper.py

示例12: get

    def get(self):
        auth_level = self.is_user_authorized()
        if auth_level == models.AUTH_LEVEL_REGISTERED_USER:
            self.redirect('/account/activate/reminder/')
        elif auth_level == models.AUTH_LEVEL_ACTIVATED_USER:
            today = datetime.utcnow()

            request_year = self.request.get('year')
            request_month = self.request.get('month')

            if not request_year or not request_month:
                year = today.year
                month = today.month
                articles = Article.get_latest_published_student()
            else:
                year = dec(request_year)
                month = dec(request_month)
                articles = Article.get_all_published_student_articles_for_month(year, month)
            books = Book.get_latest(count=10)
            response = render_template('blog_students.html',
                year_list=models.BLOG_YEAR_LIST,
                month_list=models.MONTH_LIST,
                today=today,
                requested_year=year,
                requested_month=month,
                articles=articles,
                books=books)
            self.response.out.write(response)
        else:
            response = render_template('index.html')
            self.response.out.write(response)
开发者ID:spaceone,项目名称:mils-secure,代码行数:31,代码来源:handlers.py

示例13: sec_list

def sec_list(request,domain=None):
    """.. :py:method::
    webanan的各下属分类的views方法
    """
    domains_list = []
    domain_list = Domain.objects().all()
    for do in domain_list:
        domains_list.append(do.name)
    title = u'{}分类文章数量'.format(domain)
    per_dict = {}
    domain_obj = Domain.objects(name=domain).first()
    if domain_obj:
        categories = Category.objects(belong_Domain=domain_obj).all()
        article_all = 0
        for cate in categories:
            article_all = article_all + Article.objects(belong_cate=cate).count()
        for cate in categories:
            article_num = Article.objects(belong_cate=cate).count()
            per_dict[cate.name] = float(u"%.2f" % (float(article_num)/article_all))
        per_dict = OrderedDict(sorted(per_dict.items(), key=lambda t: t[1]))
    else:
        raise Http404
    return render_to_response('webanan_list.html',{
                'title': title,
                'per_dict':per_dict,
                'domains':domains_list,
                })
开发者ID:seraph0017,项目名称:maxblog,代码行数:27,代码来源:views.py

示例14: get

 def get(self, direction = 'next', page = '2', base_id = '1'):
     if page == '1':
         self.redirect(BASE_URL)
         return
     objs = Article.get_page_posts(direction, page, base_id)
     if objs:
         if direction == 'prev':
             objs.reverse()            
         fromid = objs[0].id
         endid = objs[-1].id
     else:
         fromid = endid = ''
     
     allpost =  Article.count_all_post()
     allpage = allpost/EACH_PAGE_POST_NUM
     if allpost%EACH_PAGE_POST_NUM:
         allpage += 1
     output = self.render('index.html', {
         'title': "%s - %s | Part %s"%(SITE_TITLE,SITE_SUB_TITLE, page),
         'keywords':KEYWORDS,
         'description':SITE_DECR,
         'objs': objs,
         'cats': Category.get_all_cat_name(),
         'tags': Tag.get_hot_tag_name(),
         'page': int(page),
         'allpage': allpage,
         'listtype': 'index',
         'fromid': fromid,
         'endid': endid,
         'comments': Comment.get_recent_comments(),
         'links':Link.get_all_links(),
     },layout='_layout.html')
     self.write(output)
     return output
开发者ID:wing1000,项目名称:wb3,代码行数:34,代码来源:blog.py

示例15: all_list

def all_list(request):
    """.. :py:method::
    webanan的主页views方法
    """
    domains_list = []
    domain_list = Domain.objects().all()
    for do in domain_list:
        domains_list.append(do.name)
    title = u'各主机文章数量'
    per_dict = {}
    domains = Domain.objects().all()
    article_all = Article.objects().count()
    for domain in domains:
        categories = Category.objects(belong_Domain=domain).all()
        domain_count = 0
        
        for cate in categories:
            article_num = Article.objects(belong_cate=cate).count()
            domain_count = domain_count + article_num
        per_dict[domain.name] = float(u"%.2f" % (float(domain_count)/article_all))
    per_dict = OrderedDict(sorted(per_dict.items(), key=lambda t: t[1]))
    return render_to_response('webanan_list.html',{
        'title': title,
        'per_dict':per_dict,
        'domains':domains_list,
        })
开发者ID:seraph0017,项目名称:maxblog,代码行数:26,代码来源:views.py


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