コード例 #1
0
ファイル: views.py プロジェクト: doctor608/shop
def product_create(request, values):
    shop = Shop.get(slug=values.get('slug'))

    if shop is None:
        raise NotFound()

    if request.method == 'GET':
        categories = Category.all()
        return render_template('product-form.html', {
            'categories': categories,
            'shop': shop
        })

    name = request.form.get('name')
    price = request.form.get('price')
    description = request.form.get('description')
    categories = request.form.getlist('category')
    image = request.files.get('image')

    if image and allowed_image(image.filename):
        image_name = secure_filename(image.filename)
        image.save(os.path.join(MEDIA_ROOT, image_name))
    else:
        image_name = ''

    product = Product.create(name=name,
                             price=price,
                             image=image_name,
                             shop_id=shop.id,
                             description=description)

    for category in categories:
        product.add_category(category)

    return redirect(f'/shops/{shop.slug}/products/{product.id}')
コード例 #2
0
ファイル: vote.py プロジェクト: freedomd/Head2Head
    def get(self):  
        user = users.get_current_user()
        
        if user:
            login = True
            url = users.create_logout_url(self.request.uri)
        else:
            login = False
            url = users.create_login_url(self.request.uri)
            self.redirect("/")
            return 
        
        creator = self.request.get('creator')
        category = self.request.get('category') 
        cats = Category.all()
        cats.filter('user ='******'category =', category) # get category
        c = cats.get()
        
        if c == None:
            self.redirect("/")
            return
        
        items = Item.all()
        items.ancestor(c.key()) # get all the items of c
        itemList = []
        for item in items.run():
            itemList.append(item.item)
        
        if len(itemList) > 1:
            length = len(itemList)
            i = random.randint(0, length - 1)
            j = random.randint(0, length - 1)
            while i == j:
                j = random.randint(0, length - 1)

            choice1 = itemList[i]
            choice2 = itemList[j]
            error = None
        else:
            choice1 = None
            choice2 = None
            error = "Options not enough!"
        
        template_values = {
            'user': user,
            'login': login, 
            'url': url,
            'winner': None,
            'loser': None,
            'choice1': choice1, 
            'choice2': choice2,
            'creator': creator,
            'creatorName': c.username,
            'category': category,
            'error': error
        }
        
        path = os.path.join(os.path.dirname(__file__), 'templates/vote.html')
        self.response.out.write(template.render(path, template_values))
コード例 #3
0
ファイル: category.py プロジェクト: freedomd/Head2Head
    def post(self):
        user = users.get_current_user()
        
        if user == None:
            self.redirect("/")
            return 
        
        # get category information
        category = self.request.get('newCategory') 
        if category != "":
            # check if exists
            c = Category.all()
            c.filter('user ='******'category =', category) # check
            if c.get() == None:# does not exist
                newCat = Category() # post a new category
                newCat.category = category
                newCat.user = user.email()
                newCat.username = user.nickname()
                newCat.put() # save 
            else:
                errorMessage = "Category %s already exists!" % category
                self.redirect("/category?error=%s" % errorMessage)
                return 

        self.redirect("/category")
コード例 #4
0
ファイル: item.py プロジェクト: freedomd/Head2Head
 def post(self):
     user = users.get_current_user()
     
     if user == None:
         self.redirect("/")
         return 
     
     # get category information
     category = self.request.get('category') 
     item = self.request.get('newItem')
     if item != "":
         cs = Category.all()
         cs.filter('user ='******'category =', category) # get category
         c = cs.get()
         if c != None:
             items = Item.all()
             items.filter('item =', item)
             items.ancestor(c.key())
             if items.get() == None:
                 newItem = Item(item = item, win = 0, lose = 0, rate = 0, parent = c.key()) # post a new item
                 newItem.put() # save 
             else:
                 errorMessage = "Item %s already exists!" % item
                 self.redirect("/manageCategory?category=%s&error=%s" % (category, errorMessage))
                 return 
     
     self.redirect("/manageCategory?category=%s" % category)
コード例 #5
0
ファイル: item.py プロジェクト: freedomd/Head2Head
 def post(self):
     user = users.get_current_user()
     
     if user == None:
         self.redirect("/")
         return 
     
     # get category information
     category = self.request.get('category') 
     item = self.request.get('item')
     if item != "":
         cs = Category.all()
         cs.filter('user ='******'category =', category) # get category
         c = cs.get()
         if c != None:
             items = Item.all()
             items.filter('item =', item)
             items.ancestor(c.key())
             i = items.get()
             if i == None:
                 self.redirect("/manageCategory?category=%s" % category)
                 return
             else:
                 i.delete()
     
     self.redirect("/manageCategory?category=%s" % category)
コード例 #6
0
ファイル: item.py プロジェクト: freedomd/Head2Head
 def post(self):
     user = users.get_current_user()
     
     if user == None:
         self.redirect("/")
         return 
     
     # get category information
     category = self.request.get('category') 
     item = self.request.get('item')
     newname = self.request.get(item)
     if newname != "":
         cs = Category.all()
         cs.filter('user ='******'category =', category) # get category
         c = cs.get()
         if c != None:
             items = Item.all()
             items.filter('item =', item)
             items.ancestor(c.key())
             i = items.get()
             if i != None:
                 # reset
                 i.item = newname
                 i.win = 0
                 i.lose = 0
                 i.rate = 0
                 i.put()
                 message = 'Reset "%s" successfully.' % newname
                 self.redirect("/manageCategory?category=%s&message=%s" % (category, message))
                 return
                 
     self.redirect("/manageCategory?category=%s" % category)
     # return 
コード例 #7
0
def save_edited_category():
	cat_name = request.form.get('category')
	key = request.form.get('key')
	existing = Category.all().filter('owner =',users.get_current_user())
	for e in existing:
		if e.title.lower() == cat_name.lower():
			if not str(e.key()) == key:
				error = "You already have a category with that name. Please choose a different name"
				return Response(status=400)
	category = Category.get(key)
	items_from_form = request.form.get('items').split(',')
	old_items_from_db = Item.all().ancestor(category)
	for item in old_items_from_db:
		if not item.title in items_from_form:
			db.delete(item)
		else:
			items_from_form.remove(item.title)

	for new_item in items_from_form:
		if not new_item == '':
			i = Item(parent=category,title=new_item)
			i.put()
	category.title = request.form.get('category')
	category.put()
	return jsonify(new_items = items_from_form)
コード例 #8
0
ファイル: category.py プロジェクト: freedomd/Head2Head
 def get(self):  
     user = users.get_current_user()
     
     if user:
         login = True
         url = users.create_logout_url(self.request.uri)
     else:
         login = False
         url = users.create_login_url(self.request.uri)
         self.redirect("/")
         return 
     
     userCats = Category.all()
     userCats.filter('user ='******'user': user,
         'userCats': userCats,
         'login': login, 
         'url': url,
         'isEmpty': isEmpty,
         'error': self.request.get('error'),
         'message': self.request.get('message'),
         'importMessage': self.request.get('importMessage')
     }
     
     path = os.path.join(os.path.dirname(__file__), 'templates/category.html')
     self.response.out.write(template.render(path, template_values))
コード例 #9
0
    def __init__(self):
        """load basic members using memcache"""
        logging.info("initialized")
        self.posts_tags_db=[]
        self.catdict={}
        self.posts_tags_dict={}
        self.posts=memcache.get(KEY)

      
        if self.posts is None:
            logging.info('cache is empty creating index')
            self.posts = BlogPost.all().order('-timestamp')
   
            createIndex(self.posts)
            memcache.add(KEY,self.posts)
        if isinstance(self.posts,list):self.nofposts=len(self.posts)-2
        else:self.nofposts=self.posts.count()-2
        self.tags=memcache.get(TAG)
        if self.tags is None:
            self.tags = Tag.all()
            memcache.add(TAG,self.tags)
        self.categories=memcache.get(CATEGORY)
        if self.categories is None:
            self.categories= Category.all()
            memcache.add(CATEGORY,self.categories)

        for post in self.posts:
            logging.info(['posts',post.title])
            self.posts_tags_db.extend(post.tags)
            tags=[]
            for key in post.tags:tags.append(db.get(key).tag)
            self.posts_tags_dict[post.key()]=tags
            self.catdict[post.category.key()]=post.category.category
        logging.info(['catdict',self.catdict])
        self.tagnames=list(chain.from_iterable(self.posts_tags_dict.values()))
コード例 #10
0
ファイル: forms.py プロジェクト: jbochi/depoisdavirgula
 def __init__(self, user, type, *args, **kwargs):
     super(CategoryForm, self).__init__(*args, **kwargs)
     self.fields['parent_category'].query = Category.all()\
         .filter('user ='******'type =', type)\
         .filter('parent_category =', None)\
         .order('name')
コード例 #11
0
ファイル: product_edit_or_add.py プロジェクト: Ciwara/gcommon
    def __init__(self, table_p, parent, product=None, *args, **kwargs):
        QDialog.__init__(self, parent, *args, **kwargs)

        self.table_p = table_p
        self.prod = product
        self.parent = parent
        self.filename = "Parcourire ..."
        self.path_filename = None

        if self.prod:
            self.title = u"Modification de l'article {}".format(self.prod.name)
            self.succes_msg = u"L'article <b>%s</b> a été mise à jour" % self.prod.name
            try:
                self.filename = self.prod.file_join.file_name
            except:
                pass
        else:
            self.succes_msg = u"L'article a été bien enregistré"
            self.title = u"Ajout de nouvel article"
            self.prod = Product()

        self.setWindowTitle(self.title)

        # self.code = LineEdit(self.prod.code)
        self.name_field = LineEdit(self.prod.name)
        try:
            self.category_name = Category.select().where(
                Category.name == self.prod.category.name).get().name
        except:
            self.category_name = ""
        self.category_field = LineEdit(self.category_name)

        self.number_parts_box_field = IntLineEdit(
            str(self.prod.number_parts_box))
        self.number_parts_box_field.setValidator(QIntValidator())

        completion_values = [catg.name for catg in Category.all()]
        completer = QCompleter(completion_values, parent=self)
        completer.setCaseSensitivity(Qt.CaseInsensitive)
        completer.setCompletionMode(QCompleter.UnfilteredPopupCompletion)
        self.category_field.setCompleter(completer)

        vbox = QVBoxLayout()
        formbox = QFormLayout()
        formbox.addRow(FLabel(u"Nom"), self.name_field)
        formbox.addRow(FLabel(u"Categorie"), self.category_field)
        # formbox.addRow(
        #     FLabel(u"Quantité (carton)"), self.number_parts_box_field)
        self.butt_parco = QPushButton(
            QIcon.fromTheme('document-open', QIcon('')), self.filename)
        self.butt_parco.clicked.connect(self.import_image)
        butt_cancel = Warning_btt(u"Annuler")
        butt_cancel.clicked.connect(self.cancel)
        # formbox.addRow(FLabel(u"Image"), self.butt_parco)
        butt = Button_save(u"&Enregistrer")
        butt.clicked.connect(self.add_or_edit_prod)
        formbox.addRow(butt_cancel, butt)

        vbox.addLayout(formbox)
        self.setLayout(vbox)
コード例 #12
0
ファイル: views.py プロジェクト: ssb402/Vote-or-Skip-Web-App
def save_edited_category():
    cat_name = request.form.get("category")
    key = request.form.get("key")
    existing = Category.all().filter("owner =", users.get_current_user())
    for e in existing:
        if e.title.lower() == cat_name.lower():
            if not str(e.key()) == key:
                error = "You already have a category with that name. Please choose a different name"
                return Response(status=400)
    category = Category.get(key)
    items_from_form = request.form.get("items").split(",")
    old_items_from_db = Item.all().ancestor(category)
    for item in old_items_from_db:
        if not item.title in items_from_form:
            db.delete(item)
        else:
            items_from_form.remove(item.title)

    for new_item in items_from_form:
        if not new_item == "":
            i = Item(parent=category, title=new_item)
            i.put()
    category.title = request.form.get("category")
    category.put()
    return jsonify(new_items=items_from_form)
コード例 #13
0
ファイル: main.py プロジェクト: yanzay/pagankolo
 def get(self,name):
     cat = Category.all().filter('link = ',name).get()
     posts = BlogPost.all().filter('category = ',cat.key()).order('-pub_date')
     templ_val = {
         'posts': posts,
         'active_blogs':True
     }
     self.render_to_response('index.html',templ_val)
コード例 #14
0
ファイル: forms.py プロジェクト: jbochi/depoisdavirgula
 def __init__(self, user, *args, **kwargs):
     super(IncomeForm, self).__init__(*args, **kwargs)
     self.fields['customer'].query = Customer.all().filter('user ='******'name').fetch(1000)
     self.fields['category'].query = Category.all()\
                                             .filter('user ='******'type =', 'Receita')\
                                             .order('name').fetch(1000)
コード例 #15
0
ファイル: forms.py プロジェクト: jbochi/depoisdavirgula
 def __init__(self, user, *args, **kwargs):
     super(ExpenseForm, self).__init__(*args, **kwargs)
     self.fields['account'].query = Account.all().filter('user ='******'name')
     self.fields['category'].query = Category.all()\
                                             .filter('user ='******'type =', 'Custo')\
                                             .order('name').fetch(1000)
コード例 #16
0
ファイル: vote_handler.py プロジェクト: xz565/vote-item
    def choose_category_page(self, account):
        account_key = db.Key.from_path("Account", account)
        categories = Category.all()
        categories.ancestor(account_key)

        template_values = {"account": account, "categories": categories, "logout_url": users.create_logout_url("/")}
        path = os.path.join(os.path.dirname(__file__), "choose_category.html")
        self.response.out.write(template.render(path, template_values))
コード例 #17
0
 def refetch(self):
     self.posts =BlogPost.all().order('-timestamp')
     memcache.add(KEY,self.posts)
     self.tags = Tag.all()
     memcache.add(TAG,self.tags)
     self.categories= Category.all()
     memcache.add(CATEGORY,self.categories)
     createIndex(self.posts)
コード例 #18
0
def index():
	if not users.get_current_user():
		loginout = users.create_login_url('/')
		link = "Login"
	else:
		loginout = users.create_logout_url('/')
		link = "Logout"
	categories = Category.all()
	return render_template('index.html',categories=categories,loginout=loginout,link=link)
コード例 #19
0
ファイル: views.py プロジェクト: ssb402/Vote-or-Skip-Web-App
def index():
    if not users.get_current_user():
        loginout = users.create_login_url("/")
        link = "Login"
    else:
        loginout = users.create_logout_url("/")
        link = "Logout"
    categories = Category.all()
    return render_template("index.html", categories=categories, loginout=loginout, link=link)
コード例 #20
0
ファイル: xmlHandler.py プロジェクト: freedomd/Head2Head
    def post(self):  
        user = users.get_current_user()
        
        if user == None:
            self.redirect("/")
            return 

        content = self.request.get('content')
        if content == None or content == "":
            self.redirect("/category")
            return 
        xmldoc = minidom.parseString(content)
        category = xmldoc.getElementsByTagName('CATEGORY')[0]
        categoryName = category.getElementsByTagName('NAME')[0].childNodes[0].nodeValue
        itemList = category.getElementsByTagName('ITEM')
        
        cats = Category.all()
        cats.filter("category =", str(categoryName))
        c = cats.get()
        
        if c == None: # category not exist
            newCat = Category() # create a new category
            newCat.category = categoryName
            newCat.user = user.email()
            newCat.username = user.nickname()
            newCat.put() # save
            for item in itemList:
                itemName = item.getElementsByTagName('NAME')[0].childNodes[0].nodeValue
                newItem = Item(item = itemName, win = 0, lose = 0, rate = 0, parent = newCat.key())
                newItem.put()
            importMessage = 'Import new category "%s" successfully.' % categoryName
            self.redirect("/category?importMessage=%s" % importMessage)
        else: # category exists
            items = Item.all()
            items.ancestor(c.key())
            
            oldItemNameList = []
            for item in items.run():
                oldItemNameList.append(item.item)
            
            newItemNameList = []
            for item in itemList:
                itemName = item.getElementsByTagName('NAME')[0].childNodes[0].nodeValue
                newItemNameList.append(itemName)
                if itemName not in oldItemNameList: # new item not exist
                    newItem = Item(item = itemName, win = 0, lose = 0, rate = 0, parent = c.key())
                    newItem.put()
            
            for item in items: # get old items
                if item.item not in newItemNameList: # old item not in new list, delete
                    item.delete()
                    
            importMessage = 'Import existed category "%s" successfully.' % categoryName
            self.redirect("/category?importMessage=%s" % importMessage)
コード例 #21
0
ファイル: views.py プロジェクト: doctor608/shop
def shop_detail(request, values):
    shop = Shop.get(slug=values.get('slug'))

    if shop is None:
        raise NotFound()

    categories = Category.all()

    return render_template('shop.html', {
        'shop': shop,
        'categories': categories
    })
コード例 #22
0
ファイル: views.py プロジェクト: hollerith/schoogle
def respond(request, template, params=None):
  
  if params is None:
    params = {}

  if request.LANGUAGE_CODE != 'en':
    params['is_foreign'] = request.LANGUAGE_CODE

  if not template.endswith('.html'):
    template += '.html'

  params['skin'] = settings.SKIN
  params['app_id'] = settings.APP_ID

  session_token = None
  user = users.get_current_user()  
  if user:
    params['user'] = user
    params['author'] = db.Query(Author).filter('email = ', user.email()).get()
    if users.IsCurrentUserAdmin():
      params['authsub_url'], session_token, client = check_auth(request, user)
    params['is_admin'] = True # users.IsCurrentUserAdmin() # global
    params['developer'] = ('Dev' in os.getenv('SERVER_SOFTWARE'))
    params['sign_out'] = users.CreateLogoutURL('/')
  else:
    params['sign_in'] = users.CreateLoginURL(request.path)

  params['session_token'] = session_token

  # Events
  startTime = datetime.datetime.now() + datetime.timedelta(weeks=-2)
  endTime = datetime.datetime.now() + datetime.timedelta(weeks=2)

  urlparams = 'start-min=%s&start-max=%s' % (startTime.strftime("%Y-%m-%dT%H:%M:%S"), endTime.strftime("%Y-%m-%dT%H:%M:%S"))
  url = 'http://www.google.com/calendar/feeds/%s/public/basic?' % settings.GOOGLE_ACCOUNT
  url = url + urlparams  
  
  feed = urlfetch.fetch(url)
  calendar = feedparser.parse(feed.content)
  events = calendar['entries']
  params['events'] = events

  # sidebar categories & page links
  categories = Category.all()
  categories.order("sequence")
  params['categories'] = categories

  pages = Page.all()
  pages.order("sequence")
  params['pages'] = pages

  return shortcuts.render_to_response(template, params)
コード例 #23
0
ファイル: manage_handler.py プロジェクト: xz565/vote-item
    def manage_page(self, account_key):
        categories = Category.all()
        categories.ancestor(account_key)

        items = Item.all()

        template_values = {
            'categories': categories,
            'items': items,
            'logout_url': users.create_logout_url("/")
        }
        path = os.path.join(os.path.dirname(__file__), 'manage.html')
        self.response.out.write(template.render(path, template_values))
コード例 #24
0
ファイル: views.py プロジェクト: ytrstu/niubi
def sitemap(request):
    str = """<?xml version="1.0" encoding="UTF-8"?>
            <?xml-stylesheet type="text/xsl" href="/static/xsl/sitemap.xsl"?>
            <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
               <url>
                  <loc>http://www.niubi.de/</loc>
                  <changefreq>weekly</changefreq>
                  <priority>0.9</priority>
               </url>
        """
    posts = Post.all().filter("is_published", True)
    for post in posts:
        str += (
            """<url>
                      <loc>http://www.niubi.de/post/%s/</loc>
                      <changefreq>weekly</changefreq>
                      <priority>0.8</priority>
                   </url>
                """
            % post.key().id()
        )

    categories = Category.all().order("-post_count")
    for category in categories:
        str += (
            """<url>
                      <loc>http://www.niubi.de/category/%s/</loc>
                      <changefreq>monthly</changefreq>
                      <priority>0.8</priority>
                   </url>
                """
            % category.key().id()
        )
    tags = Tag.all().order("-post_count")
    for tag in tags:
        str += (
            """<url>
                      <loc>http://www.niubi.de/tag/%s/</loc>
                      <changefreq>weekly</changefreq>
                      <priority>0.8</priority>
                   </url>
                """
            % tag.name
        )
    str += """<url>
                  <loc>http://www.niubi.de/about/</loc>
                  <changefreq>yearly</changefreq>
                  <priority>0.8</priority>
               </url>"""
    str += "</urlset>"
    return HttpResponse(str, content_type="text/xml")
コード例 #25
0
ファイル: main.py プロジェクト: yanzay/pagankolo
 def get(self):
     user = users.get_current_user()
     prof = db.GqlQuery('SELECT * FROM Profile WHERE user = :1', user).get()
     if not prof:
         unnamed = True
     else:
         unnamed = False
     categories = Category.all()
     self.templ_vals.update({
         'url': users.create_logout_url("/"),
         'unnamed':unnamed,
         'categories':categories
     })
     self.render_to_response('add_form.html', self.templ_vals)
コード例 #26
0
ファイル: shortcuts.py プロジェクト: adamantium/hic
def validate_category(handler, category_code, kind):
    logging.getLogger().setLevel(logging.DEBUG)
    query = None
    if kind is None:
        query = Category.all()
    elif kind == "forum":
        query = ForumCategory.all()
    if query is not None:
        query.filter('code =', category_code)
        result = query.get()
        if result:
            return result        
    logging.error("Category is not found. Requested category code: " + category_code)
    handler.error(500)
コード例 #27
0
ファイル: main.py プロジェクト: xz565/vote-item
    def manage_page(self):
        currt_user = users.get_current_user()
        account_key = db.Key.from_path('Account', currt_user.nickname())
        categories = Category.all()
        categories.ancestor(account_key)

        items = Item.all()

        template_values = {
            'categories': categories,
            'items': items,
            'logout_url': users.create_logout_url("/")
        }
        path = os.path.join(os.path.dirname(__file__), 'manage.html')
        self.response.out.write(template.render(path, template_values))
コード例 #28
0
def save_new_category():
	category = request.form.get('category')
	existing = Category.all().filter('owner =',users.get_current_user())
	for e in existing:
		if e.title.lower() == category.lower():
			return Response(status=400)
	else:
		items = request.form.get('items').split(',')
		cat = Category(title=category, owner=users.get_current_user())
		cat.put()
		for i in items:
			if not i == '':
				item = Item(parent=cat.key(),title=i)
				item.put()
		return Response(status=200)
コード例 #29
0
ファイル: views.py プロジェクト: ssb402/Vote-or-Skip-Web-App
def save_new_category():
    category = request.form.get("category")
    existing = Category.all().filter("owner =", users.get_current_user())
    for e in existing:
        if e.title.lower() == category.lower():
            return Response(status=400)
    else:
        items = request.form.get("items").split(",")
        cat = Category(title=category, owner=users.get_current_user())
        cat.put()
        for i in items:
            if not i == "":
                item = Item(parent=cat.key(), title=i)
                item.put()
        return Response(status=200)
コード例 #30
0
ファイル: views.py プロジェクト: qubic/myblogongae
def base_context():
    context = Context({
        'current_user':current_user(),
        'admin':admin(),
        'login_url':users.create_login_url('/blogs'),
        'logout_url':users.create_logout_url('/blogs'),
        'recent_comments':Comment.all().order('-date').fetch(5),
        'categories':Category.all(),
        'blogs_count':Blog.all().count(),
        'archives':Archive.all().order('-year').order('-month'),
        'friendlyURLs':FriendlyURL.all()
    })
    configuration=Configuration.all().fetch(1)
    if configuration:
        context.configuration=configuration[0]
    return context
コード例 #31
0
ファイル: views.py プロジェクト: ssb402/Vote-or-Skip-Web-App
def search(keywordslist):
    keywords = keywordslist.split(" ")
    categories = {}
    keys = {}
    cat_count = {}
    for key in keywords:
        for category in Category.all():
            if category.title.lower().__contains__(key.lower()):
                categories[category.title] = Item.all().ancestor(category)
                keys[category.title] = category.key()
    for key in keywords:
        for item in Item.all():
            if item.title.lower().__contains__(key.lower()):
                categories[item.parent().title] = Item.all().ancestor(item.parent())
                keys[item.parent().title] = item.parent().key()
    return render_template("search_results.html", categories=categories, keys=keys, keywords=keywordslist)
コード例 #32
0
def search(keywordslist):
	keywords = keywordslist.split(" ")
	categories = {}
	keys = {}
	cat_count = {}
	for key in keywords:
		for category in Category.all():
			if category.title.lower().__contains__(key.lower()):
				categories[category.title] = Item.all().ancestor(category)
				keys[category.title] = category.key()
	for key in keywords:
		for item in Item.all():
			if item.title.lower().__contains__(key.lower()):
				categories[item.parent().title] = Item.all().ancestor(item.parent())
				keys[item.parent().title] = item.parent().key()
	return render_template('search_results.html',categories=categories, keys=keys, keywords=keywordslist)
コード例 #33
0
ファイル: shortcuts.py プロジェクト: adamantium/hic
def sc_validate_category(category_code, kind=None):
    logging.getLogger().setLevel(logging.DEBUG)
    query = None
    if kind is None:
        logging.debug("all")
        query = Category.all()
    elif kind == "forum":
        logging.debug("forum")
        query = ForumCategory.all()
        logging.debug(query)
    if query is not None:
        logging.debug("code is about to found")
        query.filter('code =', category_code)
        result = query.get()
        return result
    else:
        logging.debug("hello!")
コード例 #34
0
ファイル: main.py プロジェクト: jbochi/depoisdavirgula
    def _handler(self, type, post=False):
        user = users.get_current_user()

        #cap first because of existing choices
        type = type[0].upper() + type[1:]

        if user:
            if post:
                form = CategoryForm(user, type, data=self.request.POST)
                if form.is_valid():
                    # Save the data, and redirect to the view page
                    category = form.save(commit=False)
                    category.user = user
                    category.type = type
                    category.put()
                    self.redirect(self.request.uri)
            else:
                form = CategoryForm(user, type)

            categories = Category.all()\
                .filter('user ='******'type =', type)\
                .order('parent_category')\
                .order('name').run()

            categories_dict = {}
            for category in categories:
                parent_category_key = Category.parent_category.get_value_for_datastore(category)
                if parent_category_key is None:
                    categories_dict[category.key()] = {'name': category.name,
                                                      'childs': {}}
                else:
                    parent = categories_dict[parent_category_key]['childs']
                    parent[category.key()] = {'name': category.name}

            path = os.path.join(os.path.dirname(__file__), 'templates/categories.html')
            self.response.out.write(template.render(path, {
                'categories': categories_dict,
                'type': type,
                'form': form,
                'user': user,
                'logout_url': users.create_logout_url("/")
            }))
        else:
            self.redirect(users.create_login_url(self.request.uri))
コード例 #35
0
ファイル: views.py プロジェクト: lvbeck/net-fish
def sitemap(request):
    str = '''<?xml version="1.0" encoding="UTF-8"?>
            <?xml-stylesheet type="text/xsl" href="/static/xsl/sitemap.xsl"?>
            <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
               <url>
                  <loc>http://www.niubi.de/</loc>
                  <changefreq>weekly</changefreq>
                  <priority>0.9</priority>
               </url>
        '''
    posts = Post.all().filter('is_published', True)
    for post in posts:
        str += '''<url>
                      <loc>http://www.niubi.de/post/%s/</loc>
                      <changefreq>weekly</changefreq>
                      <priority>0.8</priority>
                   </url>
                ''' % post.key().id()

    categories = Category.all().order('-post_count')
    for category in categories:
        str += '''<url>
                      <loc>http://www.niubi.de/category/%s/</loc>
                      <changefreq>monthly</changefreq>
                      <priority>0.8</priority>
                   </url>
                ''' % category.key().id()
    tags = Tag.all().order('-post_count')
    for tag in tags:
        str += '''<url>
                      <loc>http://www.niubi.de/tag/%s/</loc>
                      <changefreq>weekly</changefreq>
                      <priority>0.8</priority>
                   </url>
                ''' % tag.name
    str += '''<url>
                  <loc>http://www.niubi.de/about/</loc>
                  <changefreq>yearly</changefreq>
                  <priority>0.8</priority>
               </url>'''
    str += '</urlset>'
    return HttpResponse(str, content_type='text/xml')
コード例 #36
0
ファイル: views.py プロジェクト: doctor608/shop
def product_update(request, values):
    shop = Shop.get(slug=values.get('slug'))
    product = Product.get(pk=values.get('id'))
    product_categories = [category.id for category in product.get_categories()]

    if shop is None or product is None:
        categories = Category.all()
        return render_template(
            'product-form.html', {
                'categories': categories,
                'shop': shop,
                'product': product,
                'product_categories': product_categories,
            })

    name = request.form.get('name')
    price = request.form.get('price')
    description = request.form.get('description')
    categories = request.form.getlist('category')
    image = request.files.get('image')

    if image and image.filename != product.image:
        if allowed_image(image.filename):
            image_name = secure_filename(image.filename)
            image.save(os.path.join(MEDIA_ROOT, image_name))
            if product.image != '':
                os.remove(os.path.join(MEDIA_ROOT, product.image))
        else:
            image_name = ''
    else:
        image_name = ''

    product.update(
        name=name or product.name,
        price=price or product.price,
        description=description or product.description,
        image=image_name or product.image,
    )

    # TODO: update categories

    return redirect(f'/shops/{shop.slug}/products/{product.id}')
コード例 #37
0
ファイル: views.py プロジェクト: proming/myblogongae
def base_context():
    context = Context(
        {
            "current_user": current_user(),
            "admin": admin(),
            "login_url": users.create_login_url("/blogs"),
            "logout_url": users.create_logout_url("/blogs"),
            "recent_comments": Comment.all().order("-date").fetch(5),
            "categories": Category.all(),
            "blogs_count": Blog.all().count(),
            "archives": Archive.all().order("-year").order("-month"),
            "friendlyURLs": FriendlyURL.all(),
        }
    )
    configuration = Configuration.all().fetch(1)
    if configuration:
        context.configuration = configuration[0]
    else:
        context.configuration = False
    return context
コード例 #38
0
def handleApost(id):
    posts=memcache.get(KEY)
    tags=memcache.get(TAG)
    categories=memcache.get(CATEGORY)
        
    if not posts:
      
        posts = BlogPost.all().order("-timestamp").fetch(20)
        memcache.add(KEY,posts)

    if not tags:
        tags = Tag.all().fetch(20)
        memcache.add(TAG,tags)
    if not categories:
        categories= Category.all().fetch(20)
        memcache.add(CATEGORY,categories)
        
    obj=BlogPost.get_by_id(int(id))
    tagkeys=obj.tags
    
    if request.method=="GET":
        apost=APost(id=id)
        data=apost.retrieve()
        return jsonify(msg="OK",posts=data)
    elif users.is_current_user_admin() and request.method=="DELETE":
        apost=APost(id=id)
        apost.delete()
        return jsonify(msg="OK")
        
    elif  users.is_current_user_admin() and request.method=="PUT":
        title=request.json['title']
        body=request.json['body']
        date=request.json['date']
        category=request.json['category']
        posttags=request.json['tags']
        apost=APost(title,body,date,category,posttags,id)
        (data,returnedTags)=apost.update()
       
            
       
        return jsonify(msg="OK",tags=returnedTags,posts=data)
コード例 #39
0
def edit():
	categories = Category.all().filter('owner = ',users.get_current_user())
	return render_template('edit.html',categories=categories)
コード例 #40
0
ファイル: test_orm.py プロジェクト: vskavronsky/DevClub
    def test_all(self):
        test_list = Category.all()
        test_class = self.category.__class__

        for cat in test_list:
            self.assertIs(type(cat), test_class)
コード例 #41
0
ファイル: viewmodels.py プロジェクト: reaandrew/GAE-Examples
	def __init__(self):
		self.categories = []
		categories = Category.all()

		for category in categories:
			self.categories.append(ForumCategoryViewModel(category,ForumsViewModel(category)))