def _update_or_create_item(self, **kwds): item_options_list = [ 'price', 'wholesale_price', 'quantity', 'barcode', 'identifier', 'short_description', 'name', 'slug', ] item_options = {} for k, v in kwds.iteritems(): if k in item_options_list: item_options[k] = v item_options['slug'] = urlify(kwds['name']) if kwds['identifier'] in self.data['item_by_identifier']: item = self.data['item_by_identifier'][kwds['identifier']] for k, v in item_options.iteritems(): setattr(item, k, v) item.save() self.data['item_by_identifier'].update({item.identifier: item}) logging.debug('[U] %s' % kwds['name']) # True if created return False else: item = Item(**item_options) item.save() tree_item = TreeItem(parent=kwds['parent'], content_object=item) tree_item.save() self.data['item_by_identifier'].update({item.identifier: item}) logging.debug('[S] %s' % item.name) # True if created return True
def add_item(item, box_name_text): try: box_name = BoxName.objects.get(name=box_name_text) except: print '[ERROR] BoxName not found' try: item = Item.objects.get(name=item, box_name=box_name) except: item = Item(name=item, box_name=box_name) item.save() return item
def item_add(request, article_id): categories = Category.objects.all().order_by('name') item = Item() item.article = get_object_or_404(Article, pk=article_id) articles = Article.objects.all().order_by('name') context = { 'categories': categories, 'item': item, 'articles': articles, 'STATE_CHOICES': STATE_CHOICES, 'CONDITION_CHOICES': CONDITION_CHOICES, } return render(request, 'item_add.html', context)
def go_prices(xmldoc, log): itemslist = xmldoc.getElementsByTagName(u'Предложение') for i in itemslist: id = i.attributes[u'ИдентификаторТовара'].value price = i.attributes[u'Цена'].value if Item.has_id_1c(id): it = Item.get_by_id_1c(id) it.price = float(price) it.save() else: log.append(u'Не обновлена цена для товара с идентификатором %s.'% id) log.append(u'Цены для товаров обновлены успешно.')
def create_items(): for item in ITEMS: new_item = Item(name=item['name'], description=item['description'], user_id=item['user_id'], catalog_id=item['catalog_id']) db.session.add(new_item) db.session.commit()
def seed_db(): user1 = User(name='user1', email='*****@*****.**') user2 = User(name='user2', email='*****@*****.**') db.session.add(user1) db.session.add(user2) db.session.commit() categories_data = [ {'name': 'Football'}, {'name': 'Tennis'}, ] for categories in categories_data: new_category = Category(name=categories['name']) db.session.add(new_category) db.session.commit() items_data = [ {'name': 'Ball', 'description': 'Football', 'category_id': 1}, {'name': 'Net', 'description': 'Football', 'category_id': 1}, {'name': 'Racket', 'description': 'Tennis', 'category_id': 2}, {'name': 'Tennis ball', 'description': 'Football', 'category_id': 2}, ] for index, item in enumerate(items_data): new_item = Item(name=item['name'], description=item['description'], category_id=item['category_id'], user_id=(index % 2 + 1)) db.session.add(new_item) db.session.commit()
def add_to_cart(user, item, count=1): alr = Cart.objects.filter(user=user, item=item) if len(alr) == 0: Cart(user=user, item=Item.get(item), count=count).save() else: alr[0].count = alr[0].count + count alr[0].save()
def category_filter(request, slug): c = get_common_context(request) if 'category' in request.POST: slug = request.POST['category'] if slug: c['category'] = Category.get_by_slug(slug) items = Item.objects.filter(category__in=c['category'].get_descendants(include_self=True)) for k in request.POST.keys(): if k.startswith('parametr_'): p_id = k[9:] p_value = request.POST[k] if p_id == 'price_from' and p_value: items = items.filter(price__gte=float(p_value)) c['price_from'] = int(p_value) elif p_id == 'price_to' and p_value: items = items.filter(price__lte=float(p_value)) c['price_to'] = int(p_value) else: items = Item.filter_by_parametr(items, p_id, p_value) else: items = Item.objects.all() if 'q' in request.POST: items = items.filter(name__icontains=request.POST['q']) c['items'] = items return render_to_response('catalog.html', c, context_instance=RequestContext(request))
def get_content(self, cap): res = [] for i in self.__request.session.keys(): if i.startswith('cart_'): res.append({'item': Item.get(int(i[5:])), 'count': int(self.__request.session[i])}) return res
def new_item(): """Creates new item.""" form = ItemForm(request.form) categories = db.query(Category).order_by(Category.name).all() form.category_id.choices = [(c.id, c.name) for c in categories] if request.method != 'POST' or not form.validate(): return render_template('api/new_item.html', form=form) form_file = request.files[form.image.name] img_filename = None if form_file: filename = secure_filename(form_file.filename) filename = generate_unique_filename(filename) form_file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) img_filename = filename new_item = Item(name=form.name.data, description=form.description.data, category_id=form.category_id.data, image=img_filename, user_id=session['user_id']) db.add(new_item) db.commit() flash(message="Item successfully created", category="success") return redirect(url_for('api.view_item', item_id=new_item.id))
def new_item(): """ displays form to create a new item """ return render_template('item_form.html', item=Item(), categories=Category.query.all(), target_url=url_for('new_item_save'))
def store(user_id): """ Store item to database. params: user_id: foreign key that should exists in table users.id """ form = ItemForm() if not form.validate(): return ItemController.message(False, form.errors) item = Item() item.name = form.name.data.strip() item.description = form.description.data item.category_id = CategoryHash.decode(form.category_id.data) item.user_id = user_id db.session.add(item) if item.commit_changes(): return ItemController.message(True, item) else: return ItemController.message( False, 'Could not save \ the given item.')
def item_page(request, item_id): c = get_common_context(request) if request.method == "POST": if request.POST["action"] == "add_in_basket": c["cart_working"].add_to_cart(request.user, request.POST["item_id"]) messages.success(request, u"Товар был добавлен в корзину.") return HttpResponseRedirect(request.get_full_path()) c["item"] = Item.get(item_id) return render_to_response("item.html", c, context_instance=RequestContext(request))
def create_item(request, box_name, item_name, description): if box_name == '' or item_name == '': return simplejson.dumps({'message': 'Box Name and item name are required.', 'success': 0}) try: box = BoxName.objects.get(name=box_name) except BoxName.DoesNotExist: return simplejson.dumps({'message':'Box Name "%s" does not exist' % box_name, 'success': 0}) if Item.objects.filter(name=item_name).filter(box_name = box).count() > 0: return simplejson.dumps({'message':'Item "%s" already exists' % item_name, 'success': 0}) new_item = Item(name=item_name, description=description, box_name=BoxName.objects.get(name=box_name)) new_item.save() return simplejson.dumps({'message':'%s has been added.' % item_name, 'success': 1})
def pop_content(self): res = [] for i in self.__request.session.keys(): if i.startswith('cart_'): item = i[5:] res.append({'item': Item.get(int(item)), 'count': int(self.__request.session[i])}) del self.__request.session[i] return res
def search(request): c = get_common_context(request) if request.method == 'POST': q = request.POST.get('q', '') if q: c['q'] = q c['s_categories'] = Category.search(q) c['s_items'] = Item.search(q) return render_to_response('search_res.html', c, context_instance=RequestContext(request)) return HttpResponseRedirect('/')
def present_item(self, cap, item): res = [] for i in self.__request.session.keys(): if i.startswith('cart_' + str(item)): item = i[5:] item = Item.get(int(item)) res.append({'item': item, 'count': int(self.__request.session[i]), 'sum': int(self.__request.session[i]) * self.get_price(cap, item)}) return res
def get_content(self): res = [] for i in self.__request.session.keys(): if i.startswith('cart_'): item = Item.get(int(i[5:])) count = int(self.__request.session[i]) res.append({'item': item, 'count': count, 'sum': item.price*count}) return res
def pop_content(self): res = [] for i in self.__request.session.keys(): if i.startswith('cart_'): item, size = get_item_and_size(i[5:]) if size == '0': size = None res.append({'item': Item.get(int(item)), 'size': size, 'count': int(self.__request.session[i])}) del self.__request.session[i] return res
def item(request, slug): c = get_common_context(request) if request.method == 'POST': if request.POST['action'] == 'add_in_basket': c['cart_working'].add_to_cart(request.user, request.POST['item_id'], 1) return HttpResponseRedirect(request.get_full_path()) c['item'] = Item.get_by_slug(slug) c['category'] = c['item'].category c['same'] = Item.objects.filter(category__in=c['category'].get_descendants(include_self=True)).order_by('?')[0:4] c['in_cart'] = c['cart_working'].present_item(request.user, c['item'].id) return render_to_response('item.html', c, context_instance=RequestContext(request))
def item_save(request, item_id): categories = Category.objects.all().order_by('name') error = False error_message = [] if(item_id == 0 or item_id == '0'): item = Item() item.state = STATE_AVAILABLE else: item = get_object_or_404(Item, pk=item_id) item.name = request.POST['name'] item.description = request.POST['description'] item.condition = request.POST['condition'] if len(item.name) == 0: error = True error_message.append("El nombre es requerido") if len(item.condition) == 0: error = True error_message.append("La condicion es requerida") article_id = request.POST['article'] if article_id != 0 and article_id != '0': item.article = Article.objects.get(id=article_id) else: item.article = None if error: articles = Article.objects.all().order_by('name') context = { 'categories': categories, 'item': item, 'error_message': error_message, 'articles': articles, } return render(request, 'item_add.html', context) else: item.save() article = Article.objects.get(pk=item.article.id) context = { 'categories': categories, 'article': article, 'success_message': 'El item ' + item.name + ' ha sido eliminado exitosamente.', } return render(request, 'article.html', context)
def present_item(self, cap, item): res = [] for i in self.__request.session.keys(): if i.startswith('cart_' + str(item)): item, size = get_item_and_size(i[5:]) if size == '0': size = None item = Item.get(int(item)) res.append({'item': item, 'size': size, 'count': int(self.__request.session[i]), 'sum': int(self.__request.session[i]) * self.get_price(cap, item)}) return res
def create_item(self, item_params): try: target_tree_item = TreeItem.objects.get(name=u'Импорт') except TreeItem.DoesNotExist: target_tree_item = TreeItem(parent_id=None, name=u'Импорт') target_tree_item.save() target_section = Section(is_meta_item=False) target_section.save() target_tree_item.section = target_section target_tree_item.save() new_tree_item = TreeItem(name=item_params['name'][:200], parent=target_tree_item) new_item = Item( price=item_params['price'], identifier=item_params['identifier'], quantity=item_params['quantity'], ) new_tree_item.save() new_item.save() new_tree_item.item = new_item new_tree_item.save()
def create_item(self, item_params): try: target_tree_item = TreeItem.objects.get(name=u'Импорт') except TreeItem.DoesNotExist: target_tree_item = TreeItem(parent_id=None, name=u'Импорт') target_tree_item.save() target_section = Section(is_meta_item=False) target_section.save() target_tree_item.section = target_section target_tree_item.save() new_tree_item = TreeItem(name = item_params['name'][:200], parent=target_tree_item) new_item = Item( price = item_params['price'], identifier = item_params['identifier'], quantity = item_params['quantity'], ) new_tree_item.save() new_item.save() new_tree_item.item = new_item new_tree_item.save()
def item(request, slug): c = get_common_context(request) item = Item.get_by_slug(slug) c['category'] = item.category page = c['category'] breadcrumbs = [] while page: breadcrumbs.append(page) page = page.parent breadcrumbs.reverse() c['titles'] = breadcrumbs c['item'] = item return render_to_response('item.html', c, context_instance=RequestContext(request))
def new_item_save(): """ saves the new item to db """ form = request.form item = Item() item.category_id = int(form['category']) item.title = form['title'] item.description = form['description'] item.created_at = datetime.now() item.user_id = current_user.id db.session.add(item) db.session.commit() return redirect(url_for('index'))
def test_edit_item(self, client, app): # Prepare testing edit_info = { 'name': 'edited item', 'description': 'desc', 'category_id': 1 } with app.app_context(): item = db.session.query(Item).first() other_item = db.session.query(Item)\ .filter(Item.id != item.id, Item.category_id == item.category_id).first() auth_user = item.user auth_token = get_access_token(auth_user) unauth_user = db.session.query(User).filter( User.id != auth_user.id).first() unauth_token = get_access_token(unauth_user) # Case anonymous user response = edit_item(client, item.id, edit_info) assert response.status_code == 401 # Case unauthorized user response = edit_item(client, item.id, edit_info, unauth_token) assert response.status_code == 401 # Case authorized user response = edit_item(client, item.id, edit_info, auth_token) data = response.get_json() assert response.status_code == 200 assert data['item']['name'] == edit_info['name'] with app.app_context(): db_item = Item.get_by_id(item.id) assert db_item.name == edit_info['name'] # Case duplicate item edit_info['name'] = other_item.name response = edit_item(client, item.id, edit_info, auth_token) assert response.status_code == 400 # Case invalid info edit_info['name'] = ' ' response = edit_item(client, item.id, edit_info, auth_token) assert response.status_code == 400 assert 'error' in response.get_json()
def create(self, request, id, multiverse_id): name = Card.objects.get(multiverse_id=multiverse_id).card_details.name catalog = Catalog.objects.get(id=id) if catalog.items.filter(identifier=multiverse_id).count() == 0: item = Item(name=name, quantity=1, identifier=multiverse_id) item.save() catalog.items.add(item) else: item = catalog.items.get(identifier=multiverse_id) item.quantity = item.quantity + 1 item.save() return HttpResponse(json.dumps({"success": True}), content_type="application/json")
def newItem(): """ Create a new item """ # user must be authenticated if 'user_id' not in session: return redirect('/login') form = ItemForm() categories = db_session.query(Category.id, Category.name).all() form.category_id.choices = categories if form.validate_on_submit(): # check that name != 'new', which is used for routing if form.name.data.lower() == 'new': form.name.errors.append("'new' is a reserved word, and cannot" " be used as an item name.") return render_template('new_item.html', form=form) filename = None # check if user uploaded file and sanitize filename if form.image.has_file(): # get the filename, ensuring that it is safe filename = secure_filename(form.image.data.filename) form.image.data.save( os.path.join(app.config['UPLOAD_FOLDER'], filename)) # create new item and commit to database item = Item( name=form.name.data, description=form.description.data, category_id=form.category_id.data, image=filename, user_id=session['user_id'], pub_date=datetime.utcnow() ) db_session.add(item) try: db_session.commit() except exc.IntegrityError: # item name should be unique db_session.rollback() form.name.errors.append("Item already exists.") return render_template('new_item.html', form=form) flash("Created new item %s." % item.name) return redirect(url_for('item', name=item.name)) return render_template('new_item.html', form=form)
def create_item(): """Create new item""" payload = g.get('payload') name, description, category_id = (payload['name'], payload['description'], payload['category_id']) exist_item = db.session.query(Item) \ .filter(Item.name == name, Item.category_id == category_id)\ .first() if exist_item is not None: return render_json_error('Item\'s name existed in this category') item = Item(name=name, description=description, category_id=category_id, user_id=g.current_user.id) db.session.add(item) db.session.commit() return render_json({'item': item_schema.dump(item).data}, 201)
def addCategoryItem(categoryName): try: category = Category.query.filter_by(name=categoryName).first() if current_user.id == category.user_id or current_user.admin: if request.method == 'GET': return render_template('new_item.html', category=category, user=current_user) elif request.method == 'POST': if (request.form['name'] and request.form['picture'] and request.form['description']): newItem = Item(name=request.form['name'], picture=request.form['picture'], description=request.form['description'], category_id=category.id, category_name=category.name, user_id=current_user.id) db.session.add(newItem) db.session.commit() flash({ "message": "New item successfully created.", "role": "success" }) return redirect(url_for('main.showHome')) else: flash({ "message": "Please fill in all the fields!", "role": "failure" }) return render_template('new_item.html', category=category, user=current_user) else: return handleUnauthorized() except exc.SQLAlchemyError as e: flash({ "message": "No category found. Please add a category before" + " adding items.", "role": "failure" }) return redirect(url_for('main.showHome'))
def items(): form = ItemForm() if form.validate_on_submit(): if form.new_category.data: new_category = Category(form.new_category.data) db.session.add(new_category) db.session.flush() category = new_category elif form.category.data: category_id = form.category.get_pk(form.category.data) category = Category.query.filter_by(id=category_id).first() else: category = None catalog = Catalog.query.first() author = Author.query.filter_by(username=session['username']).first() title = form.title.data description = form.description.data slug = slugify(title) item = Item(catalog, author, title, description, category, slug) db.session.add(item) db.session.commit() return redirect(url_for('article', slug=slug)) return render_template('catalog/items.html', form=form, action="new")
def test_delete_item(self, client, app): # Prepare testing with app.app_context(): item = db.session.query(Item).first() auth_user = item.user auth_token = get_access_token(auth_user) unauth_user = db.session.query(User).filter( User.id != auth_user.id).first() unauth_token = get_access_token(unauth_user) # Case anonymous user response = delete_item(client, item.id) assert response.status_code == 401 # Case unauthorized user response = delete_item(client, item.id, unauth_token) assert response.status_code == 401 # Case authorized user response = delete_item(client, item.id, auth_token) assert response.status_code == 204 with app.app_context(): db_item = Item.get_by_id(item.id) assert db_item is None
def item_create(category_id): """ This creates a new item only if the user is logged in """ if not logged_in(): flash('Please log in to create items') return redirect(url_for('category_list')) form = ItemForm() if form.validate_on_submit(): item = Item() item.title = form.title.data item.description = form.description.data item.category_id = category_id item.ctlg_user = get_current_user() db.session.add(item) db.session.commit() return redirect(url_for('item_create', category_id=category_id)) return render_template('item_create.html', form=form, category_id=category_id)
category2 = Category(name="Electronics") db.add(category2) category3 = Category(name="Food") db.add(category3) category4 = Category(name="Miscellaneous") db.add(category4) db.commit() add_item( category1, Item(user=user, name="Data Structures Algorithms Design", description="Great book!")) add_item( category1, Item(user=user, name="Harry Potter", description="Did you see the movie?")) add_item( category1, Item(user=user, name="Romeo and Juliet", description="Classic love story.")) add_item(category2, Item(user=user, name="Android phone", description="Awsome phone.")) add_item(category2, Item(user=user, name="Laptop", description="Who needs a computer?")) add_item( category2,
category2 = Category(name = "Electronics") db.add(category2) category3 = Category(name = "Food") db.add(category3) category4 = Category(name = "Miscellaneous") db.add(category4) db.commit() # Sample items add_item(category1, Item(user = user, name = "Data Structures and Network Algorithms", description = "This is a great book!")) add_item(category1, Item(user = user, name = "Ender's Game", description = "Did you see the movie? I only read the book.")) add_item(category1, Item(user = user, name = "Romeo and Juliet", description = "Classic love story.")) add_item(category2, Item(user = user, name = "Smart phone", description = "Pretty cool phone.")) add_item(category2, Item(user = user, name = "Tablet", description = "Who needs a computer?")) add_item(category2, Item(user = user, name = "DVD player", description = "Sorry, no blu-ray here, but still cool :)")) add_item(category3, Item(user = user, name = "Banana", description = "This is a yellow banana.")) add_item(category3, Item(user = user, name = "Apple", description = "This is a red apple.")) add_item(category3, Item(user = user, name = "Orange", description = "This is an orange orange.")) add_item(category4, Item(user = user, name = "Pen", description = "A pen. Pretty useful for writing notes on paper.")) add_item(category4, Item(user = user, name = "Pencil", description = "This can be pretty handy if you need to erase things you write.")) add_item(category4, Item(user = user, name = "Notepad", description = "Combined with a pen or pencil, can be used to write anything you want.")) add_item(category4, Item(user = user, name = "Playing cards", description = "Standard 52 card deck. What games do you like to play?"))
db.add(category2) category3 = Category(name="Music Arts") db.add(category3) category4 = Category(name="Calligraphy") db.add(category4) category5 = Category(name="Strategy Arts(board games)") db.commit() add_item( category1, Item(user=user, name="Kung Fu", description="Learnt by skill and practice.")) add_item( category1, Item(user=user, name="Martial Art", description="The Military Kung Fu.")) add_item( category1, Item(user=user, name="Law of the fist", description="Basically Curled Finger skills.")) add_item( category2, Item( user=user, name="Gongbi(meticulous)",
def main(): #drop the database tables #create the database and the tables db.drop_all() db.create_all() # Create stock, out of the box user UserArtV = User(name="Art Vandalay", email="*****@*****.**", picture="/static/costanza.jpg") db.session.add(UserArtV) db.session.commit() category1 = Category(name="Soccer") db.session.add(category1) db.session.commit() category2 = Category(name="Basketball") db.session.add(category2) db.session.commit() category3 = Category(name="Baseball") db.session.add(category3) db.session.commit() category4 = Category(name="Frisbee") db.session.add(category4) db.session.commit() category5 = Category(name="Snowboarding") db.session.add(category5) db.session.commit() category6 = Category(name="Rock Climbing") db.session.add(category6) db.session.commit() category7 = Category(name="Foosball") db.session.add(category7) db.session.commit() category8 = Category(name="Skating") db.session.add(category8) db.session.commit() category9 = Category(name="Hockey") db.session.add(category9) db.session.commit() item1 = Item(user_id=1, name="Stick", description="Interdum odio dignissim in nisi metus\ , a elit sit dis cubilia, fringilla praesent pulvinar porta.\ Sodales hac bibendum", category=category9) db.session.add(item1) db.session.commit() item2 = Item( user_id=1, name="Goggles", description="Primis dignissim mattis erat bibendum eu arcu quis\ cursus", category=category5) db.session.add(item2) db.session.commit() item3 = Item(user_id=1, name="Snowboard", description="Curae feugiat netus auctor lacus", category=category5) db.session.add(item3) db.session.commit() item4 = Item(user_id=1, name="Soccer Item 1", description="Nec odio consectetur cum \ consequat quam massa habitant placerat, nam tincidunt mi egestas \ eu taciti velit dictum aenean, vestibulum inceptos semper \ penatibus proin fringilla quisque. Cursus ridiculus facilisis \ class erat varius cum consequat, ac at justo mattis magna dui \ suscipit interdum, faucibus auctor rhoncus diam parturient a.", category=category1) db.session.add(item4) db.session.commit() item5 = Item(user_id=1, name="Soccer Item 2", description="Fermentum scelerisque \ facilisis tortor rhoncus magna maecenas, blandit ligula metus \ amet congue fames pulvinar, eget aliquam augue eros per. Vel \ etiam dolor ornare aliquet posuere inceptos maecenas nam, varius \ eget ad imperdiet mi phasellus turpis nisl libero, urna \ tristique aptent ultricies taciti montes parturient.", category=category1) db.session.add(item5) db.session.commit() item6 = Item(user_id=1, name="Soccer Item 3", description="Placerat primis taciti etiam \ ut convallis accumsan lorem tortor sapien faucibus cursus, quam \ nulla tempor morbi rhoncus suscipit sociis in litora amet enim, \ praesent aptent bibendum integer ornare dapibus justo rutrum \ aliquet vivamus. Taciti dignissim neque euismod elit maecenas \ aptent interdum mollis vel sociosqu donec, nunc gravida eget ad \ quisque viverra vitae amet hendrerit.", category=category1) db.session.add(item6) db.session.commit() item7 = Item(user_id=1, name="Soccer Item 4", description="Litora turpis et dignissim \ nascetur faucibus taciti vivamus interdum, tempor dapibus lorem \ venenatis enim conubia lacus netus hac, dis magnis vel nulla \ phasellus bibendum fringilla. Sed torquent taciti accumsan elit \ sagittis nulla magnis, sit praesent volutpat nam consectetur \ velit, magna sociis id ultrices diam non.", category=category1) db.session.add(item7) db.session.commit() item8 = Item(user_id=1, name="Frisbee", description="Interdum odio dignissim in nisi \ metus, a elit sit dis cubilia, fringilla praesent pulvinar \ porta. Sodales hac bibendum tincidunt risus mus himenaeos erat \ ac, mollis semper integer tempor lacus turpis libero, ridiculus \ primis curae aliquet nec rhoncus ante.", category=category4) db.session.add(item8) db.session.commit() item9 = Item(user_id=1, name="Bat", description="Primis dignissim mattis erat bibendum eu arcu \ quis cursus", category=category3) db.session.add(item9) db.session.commit() #commit changes db.session.commit() print "Added Categories, Items, and a User."
def add_items(category, item_names): """Add a list of items to a category.""" for name in item_names: item = Item(name = name, category_id = category.id) db.add(item) db.commit()
('Compound Benzoin Tincture Swabsticks','Z', True,False), ('Skin Protectant Swabsticks','Z', True,False), ('Skin Prep Pads & Protective Barrier Wipes','Z', True,False), ('Petroleum Jelly','Z', True,False), ('Q-Tips & Cotton-Tipped Applicators','Z', True,False), ('Tongue Depressors','Z', True,False), ('Band-Aids, Steri-Strips','Z', True,False), ('Blades/Scalpels','Z', True,False), ('Fish/Bowel Protector','Z', True,False), ('Goggles','Z', True,True), ('Hot/Cold Packs','Z', True,True), ('Lubricating Gel & Surgical Lubricant','Z', True,False), ('Spill Kits','Z', True,True), ('Ultrasound Gel','Z', True,False), ('Large Equipment','#',False,False), ('Small Equipment','#',False,False) ) for pair in box_name_mapping: box_name = BoxName(name=pair[0], category=Category.objects.get(letter=pair[1]), can_expire=pair[2], can_count=pair[3]) box_name.save() item_file = file('/var/www/MediVol/catalog/item_list.txt', 'r') box_name = None for line in item_file: if ':' in line: box_name = BoxName.objects.get(name=line.split(":")[0]) else: item = Item(box_name=box_name, name=line.strip(), description='') item.save()
def decorated_func(item_id, **kwargs): item = Item.get_by_id(item_id) if item is None: return render_json_error('Item not found', 404) return f(item_id, item, **kwargs)
category3 = Category(name="Fruits & Vegetables") db.add(category3) category4 = Category(name="More Fruits & Vegetables") db.add(category4) db.commit() # Sample items add_item( category1, Item( user=user, name="Parlsey", description= "A biennial plant that will return to the garden year after year once it is established." )) add_item( category1, Item(user=user, name="Sage", description= "A perennial, evergreen subshrub, with woody stems, grayish leaves.")) add_item( category1, Item( user=user, name="Rosemary", description= "A woody, perennial herb with fragrant, evergreen, needle-like leaves."
def add_items(category, item_names): for name in item_names: item = Item(name=name, category_id=category.id) db.add(item) db.commit()
def item(request, slug): c = get_common_context(request) c['item'] = Item.get_by_slug(slug) c['category'] = c['item'].category c['title'] = c['item'].name return render_to_response('item.html', c, context_instance=RequestContext(request))
db.session.add(user) db.session.commit() print "User - Sophie Reddimalla created ID=" + str(user.id) print "Creating Sample Category Football ..." category = Category() category.title = "Football" category.user_id = user.id category.created = datetime.utcnow() category.modified = datetime.utcnow() db.session.add(category) db.session.commit() print "Category - Football created ID=" + str(category.id) print "Creating Sample Items in Football ..." item = Item() item.category_id = category.id item.title = "Soccer Ball" item.description = "High Quality ,Tournament grade" item.created = datetime.utcnow() item.modified = datetime.utcnow() item.user_id = user.id db.session.add(item) db.session.commit() print "Item - %s created ID=%d" % (item.title, item.id) print "Creating Sample Items in Football ..." item = Item() item.category_id = category.id item.title = "Studs - Reebok" item.description = "Imported Studs from Taiwan"
vehicles = Tag(name='Vehicles', user_id=1) db_session.add(vehicles) boats = Tag(name='Boats', user_id=1) db_session.add(boats) db_session.commit() # Create items print "Creating items." i1 = Item(name='Dictionary', description='The latest Oxford dictionary', tags=[books, nonfiction], user_id=1, picture_url = "http://ecx.images-amazon.com/images/I/51RmpdfuGRL._SX379_BO1,204,203,200_.jpg") db_session.add(i1) i2 = Item(name='Chair', description='An old antique chair', tags=[furniture], user_id=1, picture_url="https://upload.wikimedia.org/wikipedia/commons/5/52/Karin_larsson_schommelstoel.jpg") db_session.add(i2) i3 = Item(name='Coffee table', description='A perfectly ordinary coffee table', tags=[furniture], user_id=1,