Example #1
0
def items_edit(item_id):
    form = ItemForm(request.form)

    if request.method == 'POST' and form.validate():
        if Item.query.filter(Item.name == form.name.data, Item.id != form.id.data).first():
            data = {
                'nav_urls': get_urls(),
                'active_url': url_for('items_new')
            }
            duplicate = True
            return render_template('items_edit.html', form=form, data=data, duplicate=duplicate)
        else:
            item = Item.query.filter(Item.id == item_id).first()
            item.name = form.name.data
            item.price = form.price.data
            item.active = form.active.data
            dbs.add(item)
            dbs.commit()
            return redirect(url_for('items'))
    else:
        data = {
            'nav_urls': get_urls(),
            'active_url': url_for('items_edit', item_id=item_id)
        }
        item = Item.query.filter(Item.id == item_id).first()
        form.id.data = item.id
        form.name.data = item.name
        form.price.data = item.price
        form.active.data = item.active
        return render_template('items_edit.html', data=data, form=form)
Example #2
0
def item_edit(request, item_id):
    item = get_object_or_404(Item, pk=item_id)
    if item.shop != request.shop:
        raise Http404

    if request.method == 'POST':
        form = ItemForm(request, request.POST, request.FILES, prefix="item", instance=item)
        if form.is_valid():
            item = form.save()
#            for img in request.FILES.getlist('file'):
#                image = ImageItem()
#                image.item = item
#                image.image.save(img.name,img)
            request.flash['message'] = unicode(_("Item successfully edited."))
            request.flash['severity'] = "success"
        else:
            request.flash['message'] = unicode(_("Item couldn't be edited."))
            request.flash['severity'] = "error"
        
        return HttpResponseRedirect(reverse('inventory_items'))
    else:
        form = ItemForm(request, prefix="item", instance=item)
    
    form_category = MarketCategoryForm(prefix="category")
    form_sub_category = MarketSubCategoryForm(request, prefix="sub_category")
    
    return render_to_response('for_sale/item_edit.html', 
                              {'form': form,
                               'item': item,
                               'form_category': form_category,
                               'form_sub_category': form_sub_category,
                               },
                              RequestContext(request))
Example #3
0
def update_item(id):
    """Updates the requested item."""
    if needs_login():
        return redirect(url_for('oauth2callback'))
    form = ItemForm(request.form)
    item = models.Item.query.filter_by(id=id).first()
    if not form.validate():
        return render_template('edit_item.html', form=form, item=item)

    # retain the old image path before populate_obj overwrites it with form
    # data
    old_image = item.image
    form.populate_obj(item)
    item.image = old_image

    if form.image is not None:
        image_data = request.files['image'].read()
        if len(image_data) > 0:
            # generate a random file name and save it to the image folder
            filename = ''.join(random.choice(
                string.ascii_uppercase + string.digits) for x in xrange(16))
            ext = os.path.splitext(request.files['image'].filename)[1]
            open(app.config['IMAGE_DIR'] +
                 filename + ext, 'w').write(image_data)
            item.image = filename + ext
            # if the user updates the image, delete the old one
            if os.path.isfile(app.config['IMAGE_DIR'] + old_image):
                os.remove(app.config['IMAGE_DIR'] + old_image)

    db.session.add(item)
    db.session.commit()
    return render_template('generic.html',
                           title="Update Completed",
                           description="%s has been updated." % item.name,
                           redirect_to_index=True)
Example #4
0
def createItem(request):
    if request.POST:
        form = ItemForm(request.POST, request.FILES)
        if form.is_valid():
            # do not save yet, and add in default owners_id
            obj = form.save(commit=False)
            # add in the creator's id
            obj.owners = request.user
            # add item status
            obj.status = "Not Sold"
            # save data
            obj.save()

            return HttpResponseRedirect("/web/main/")
    else:
        form = ItemForm()

    args = {}
    args.update(csrf(request))

    args["form"] = form
    args["notifications"] = Notifications.objects.filter(requestedTo=request.user, state="Pending")
    args["notifications_count"] = args["notifications"].count()
    args["transactions"] = Notifications.objects.filter(requestedFrom=request.user).order_by("item", "-bid")
    args["transactions_count"] = args["transactions"].count()
    args["online_user"] = request.user

    return render_to_response("createItem.html", args)
Example #5
0
def item_store(category_name):
    """Store new item in DB"""
    if 'username' not in login_session:
        return redirect(url_for('login'))
    category = Category.query.filter(Category.name == category_name).first()
    if category.author_id != login_session['user_id']:
        return render_template('401.html', name='item')
    form = ItemForm()
    form.category_id.choices = [(c.id, c.name)
                                for c in Category.query.order_by('name')]
    form.category_id.data = category.id
    if form.validate_on_submit():
        try:
            new_item = Item(form.name.data,
                            form.description.data,
                            category.id,
                            login_session['user_id'])
            if 'image' in request.files and request.files['image']:
                filename = images.save(request.files['image'])
                new_item.image_name = filename
            db_session.add(new_item)
            db_session.commit()
            return redirect(url_for('item_view',
                                    category_name=category_name,
                                    item_name=form.name.data))
        except IntegrityError:
            db_session.rollback()
            flash("Item name must be unique value")
        except Exception, e:
            db_session.rollback()
            print e
            flash("Database error encountered")
Example #6
0
def item_form(request, id=None):
    if id:
        item = get_object_or_404(Item, id=id, company=request.company)
        scenario = 'Update'
    else:
        item = Item(purchase_account=Account.objects.get(name='Purchase', company=request.company),
                    sales_account=Account.objects.get(name='Sales', company=request.company),
                    purchase_tax_scheme=TaxScheme.objects.get(name='No Tax', company=request.company),
                    sales_tax_scheme=TaxScheme.objects.get(name='No Tax', company=request.company))
        scenario = 'Create'
    if request.POST:
        form = ItemForm(data=request.POST, instance=item, company=request.company)
        if form.is_valid():
            item = form.save(commit=False)
            item.company = request.company
            item.save()
            if request.is_ajax():
                return render(request, 'callback.html', {'obj': ItemSerializer(item).data})
            return redirect('/inventory/items/')
    else:
        form = ItemForm(instance=item, company=request.company)
    if request.is_ajax():
        base_template = 'modal.html'
    else:
        base_template = 'dashboard.html'
    return render(request, 'item_form.html', {
        'scenario': scenario,
        'form': form,
        'base_template': base_template,
    })
Example #7
0
def item_add_typed(request, type_id, response_format='html'):
    "Item add with preselected type"

    item_type = get_object_or_404(ItemType, pk=type_id)
    if not request.user.profile.has_permission(item_type, mode='x'):
        return user_denied(request, message="You don't have access to create " + unicode(item_type),
                           response_format=response_format)

    if request.POST:
        if 'cancel' not in request.POST:
            form = ItemForm(
                request.user.profile, item_type, request.POST, files=request.FILES)
            if form.is_valid():
                item = form.save(request)
                return HttpResponseRedirect(reverse('infrastructure_item_view', args=[item.id]))
        else:
            return HttpResponseRedirect(reverse('infrastructure_index'))
    else:
        form = ItemForm(request.user.profile, item_type)

    context = _get_default_context(request)
    context.update({'item_type': item_type,
                    'form': form})

    return render_to_response('infrastructure/item_add_typed', context,
                              context_instance=RequestContext(request), response_format=response_format)
Example #8
0
def item_add_edit(request, id=None):

    item = get_object_or_404(Item, pk=id) if id else None

    if request.method == "POST":
        form = ItemForm(request.POST, instance=item)
        if form.is_valid():
            item = form.save()

            # Let them know it was saved properly!
            messages.success(request, "Successfully saved item %d x %s." % (item.quantity, item.sku))

            # If they ask to add again, give them to this page
            if request.POST.get("add_and_add", None):
                return HttpResponseRedirect(reverse("item_add"))

            # Else return them to home page
            return HttpResponseRedirect(reverse("home"))
        else:
            # Let them know there is an error
            messages.error(request, "There was an error.")
    else:
        form = ItemForm(instance=item)

    return render(request, "inventory/item_add_edit.html", {"item_form": form, "item": item})
Example #9
0
def add_item():
    """Saves the new item and redirects to confirmation page."""
    if needs_login():
        return redirect(url_for('oauth2callback'))
    form = ItemForm(request.form)
    if not form.validate():
        return render_template('new_item.html', form=form)

    image = ""
    if form.image.data is not None:
        image_data = request.files['image'].read()
        if len(image_data) > 0:
            # generate a random file name and save it to the image folder
            filename = ''.join(random.choice(
                string.ascii_uppercase + string.digits) for x in xrange(16))
            ext = os.path.splitext(request.files['image'].filename)[1]
            open(app.config['IMAGE_DIR'] +
                 filename + ext, 'w').write(image_data)
            image = filename + ext

    item = models.Item(name=form.name.data,
                       user=get_current_user(),
                       description=form.description.data,
                       category=form.category.data,
                       image=image)

    db.session.add(item)
    db.session.commit()
    return render_template('generic.html',
                           title="Item Added",
                           description="%s has been added." % item.name,
                           redirect_to_index=True)
Example #10
0
def post_item(request):
    if request.method == 'POST':
        form = ItemForm(request.POST,  request.FILES)
        if form.is_valid():
            m_tags = form.cleaned_data['item_tags']
            m = Item(
                name=form.cleaned_data['item_name'],
                # type=form.cleaned_data['item_type'],
                # item_image=request.FILES['item_image'],
                image_first = form.cleaned_data['image_first'],
                image_second= form.cleaned_data['image_second'],
                image_third= form.cleaned_data['image_third'],
                looking_for = True if 'True' == form.cleaned_data['item_sellOrLookFor'] else False,
                category = form.cleaned_data['item_category'],
                #price=form.cleaned_data['item_price'],
                negotiable=form.cleaned_data['item_negotiable'],
                owner=request.user,
                description=form.cleaned_data['item_description']
            )
            m.save()
            print "item has been saved with item_id "+str(m.pk)
            print m_tags
            m.tags.add(*m_tags)
            # return my_items(request)
            return HttpResponseRedirect('/')

    else:
        form = ItemForm()
    return render_to_response('post_item.html', {'form': form, 'user': request.user}, context_instance=RequestContext(request))
Example #11
0
def UpdateItem(message):
	Before_request()

	list_id = message["list_id"]
	item_id = message["item_id"]

	# Before checking for validation, we assume the item will not be 
	# added and that the list is not valid.
	sendMessage = {"errors": "This is not a valid list."}
	customMessage = 'update item fail'
	room = None

	query_list = g.user.lists.filter_by(id = list_id).first()
	query_list_shared = g.user.shared_lists.filter_by(id = list_id).first()
	
	if query_list is not None or query_list_shared is not None:

		item = Item.query.filter_by(id = item_id).first()
		form = ItemForm(item_name = message["item_name"], csrf_token = message["csrf_token"])

		# We don't need the items checked state to validate the form
		del form.check

		if item is not None and form.validate():
			item.item_name = form.item_name.data
			db.session.commit()

			sendMessage = {"itemName": item.item_name, "itemID": item.id}
			customMessage = 'update item success'
			room = list_id

		else:
			sendMessage = {"errors": form.item_name.errors}

	emit(customMessage, sendMessage, room = room)
Example #12
0
def item_create(request, user_pk=None):
    if user_pk is not None and int(user_pk) == request.user.pk:
        raise Http404

    user = None
    if user_pk is not None:
        user = get_object_or_404(User, pk=user_pk)

    if request.method == 'POST':
        surprise = True
        if user is None:
            user = request.user
            surprise = False

        form = ItemForm(request.POST)
        if form.is_valid():
            obj = form.save(commit=False)
            obj.user = user
            obj.surprise = surprise
            obj.save()
            if surprise:
                buy = Buy.objects.create(user=request.user, item=obj)
                buy.save()
                return redirect('person-detail', obj.user.username)

            return redirect('index')
    else:
        form = ItemForm()

    data = {
        'form': form,
        'current_user': user
    }
    return render_to_response('new.html', data,
                              context_instance=RequestContext(request))
def item_add(request):
    if request.method == 'POST':
        form = ItemForm(request, request.POST, request.FILES, prefix="item")
        if form.is_valid():
            item = form.save(commit=False)
            item.shop = request.shop
            item.save()
            item.update_latest_item()
            for img in request.FILES.getlist('file'):
                image = ImageItem()
                image.item = item
                image.image.save(img.name,img)
            request.flash['message'] = unicode(_("Item successfully added."))
            request.flash['severity'] = "success"
            return HttpResponseRedirect(reverse('inventory_items'))
    else:
        form = ItemForm(request, prefix="item")
    form_category = MarketCategoryForm(prefix="category")
    form_sub_category = MarketSubCategoryForm(request, prefix="sub_category")
    form_session = AuctionSessionForm(prefix="session")
    sessions = AuctionSession.objects.filter(shop = request.shop)
    return render_to_response('store_admin/inventory/item_add.html', 
                              {'form': form,
                               'form_category': form_category,
                               'form_sub_category': form_sub_category,
                               'form_session': form_session,
                               'sessions': sessions,
                               },
                              RequestContext(request))
Example #14
0
def add_item(user_id):
    user = db.session.query(User).filter_by(id=user_id).first()
    tokens = map(lambda x: x.token , user.tokens)
    check = check_auth_header(request.headers)
    if not check[0]:
        return check[1]
    if not authenticate_user(tokens , request.headers['AuthToken']):
        return unauthorized_message()

    data = MultiDict(mapping=request.json)
    inputs = ItemForm(data , csrf_enabled=False)
    if not inputs.validate():
        return bad_request_error(inputs.errors)

    data = request.get_json()
    name = data['name']
    description = data['description']
    thumbnail_url = data['thumbnail_url']
    item_url = data['item_url']
    item = Item(name, description, thumbnail_url, user_id, item_url)
    db.session.add(item)
    db.session.commit()
    response = jsonify({'name':item.name , 'description':item.description, 'thumbnail_url':item.thumbnail_url})
    response.status_code = 201
    return response
Example #15
0
def item_edit(request, item_id, response_format='html'):
    "Item edit page"
    item = get_object_or_404(Item, pk=item_id)
    if not request.user.profile.has_permission(item, mode="w"):
        return user_denied(request, message="You don't have write access to this Item",
                           response_format=response_format)

    if request.POST:
        if 'cancel' not in request.POST:
            form = ItemForm(request.user.profile, item.item_type, request.POST,
                            files=request.FILES, instance=item)
            if form.is_valid():
                item = form.save(request)
                return HttpResponseRedirect(reverse('infrastructure_item_view', args=[item.id]))
        else:
            return HttpResponseRedirect(reverse('infrastructure_item_view', args=[item.id]))
    else:
        form = ItemForm(
            request.user.profile, item.item_type, instance=item)

    context = _get_default_context(request)
    context.update({'item': item,
                    'form': form})

    return render_to_response('infrastructure/item_edit', context,
                              context_instance=RequestContext(request), response_format=response_format)
Example #16
0
def add_item():
    form = ItemForm()
    if form.validate_on_submit():
        item = Items(name=form.name.data,
                     quantity=form.quantity.data,
                     description=form.description.data,
                     date_added=datetime.datetime.now())
        db_session.add(item)
        db_session.commit()
        return redirect(url_for('success'))
    return render_template('index.html', form=form)
Example #17
0
def add_item():
    form = ItemForm()
    if form.validate_on_submit():
        title = form.title.data
        description = form.description.data
        price = form.price.data
        item = models.Item(title=title, description=description, price=price)
        db.session.add(item)
        db.session.commit()
        flash("Stored '{}'".format(description))
        return redirect(url_for('index'))
    return render_template('add_item.html', form=form)
Example #18
0
def add_item():
    #raise
    form = ItemForm()
    if request.method == 'POST': 
        if form.validate_on_submit():
            item = Items(name=form.name.data, quantity=form.quantity.data, description=form.description.data, date_added=datetime.datetime.now())
            db_session.add(item)
            db_session.commit()
            logging.warn(" after committ...")
            #return redirect(url_for('success'))
            return redirect('/success')
    return render_template('index.html', form=form)
Example #19
0
def editItem(item_id):
    categories = session.query(Category).all()
    item = session.query(Item).filter_by(id=item_id).one_or_none()
    if item is None:
        flash("Item does not exist")
        return redirect(url_for('site.showHome'))

    # Checks if the current user is not the owner of the item
    if login_session['user_id'] != item.user_id:
        flash("You're not authorized to edit this item")
        return redirect(url_for('site.showHome'))

    # This loads the ItemForm into a local variable
    form = ItemForm(request.form)

    if request.method == 'GET':
        # This will render a form to edit an item
        form.name.data = item.name
        form.description.data = item.description
        return render_template('edititem.html',
                               categories=categories,
                               item=item,
                               form=form)

    if request.method == 'POST':
        # This checks whether the form passes validation
        if form.validate():
            # This will commit the item edit to the database
            item.category = item.category
            if request.form['name']:
                item.name = request.form['name']
            if request.form['description']:
                item.description = request.form['description']
            if request.form['category']:
                item.category = session.query(Category).filter_by(
                    name=request.form['category']).one_or_none()
                if item.category is None:
                    flash("Get out of dev tools, hacker!")
                    return redirect(url_for('site.showHome'))
            session.add(item)
            session.commit()

            return redirect(
                url_for('site.showItem',
                        category_name=item.category.name,
                        item_id=item.id))
        else:
            # This will run if the form fails validation
            return render_template('edititem.html',
                                   categories=categories,
                                   item=item,
                                   form=form)
Example #20
0
def items_list():
    form = ItemForm()
    error = ""
    if request.method == "POST":
        if form.validate_on_submit():
            items.create(form.data)
            items.save_all()
        return redirect(url_for("items_list"))  # noqa

    return render_template("items.html",
                           form=form,
                           items=items.all(),
                           error=error)  # noqa
Example #21
0
def publish():
    form = ItemForm()
    if form.validate_on_submit():
        item = Item(title=form.title.data,
                    detail=form.detail.data,
                    tag=form.tag.data,
                    before=form.before.data,
                    timestamp=datetime.datetime.now(),
                    user_id=current_user.id)
        db.session.add(item)
        db.session.commit()
        return redirect((url_for('index')))
    return render_template('publish.html', form=form)
Example #22
0
def add_item():
    form = ItemForm()
    if form.validate_on_submit():
        item = Items(
            name=form.name.data,
            quantity=form.quantity.data,
            description=form.description.data,
            date_added=str(datetime.datetime.now()),
        )
        db_session.add(item)
        db_session.commit()
        return redirect(url_for("success", _external=True))
    return render_template("index.html", form=form)
Example #23
0
 def post(self, vendor_name):
     # TODO: should be editing existing item if the name of item is identical with existing one
     #       upload thumb
     #       resize thumb using google.appengine.api.images
     data = ItemForm(data=self.request.POST)
     if data.is_valid():
         item = data.save(commit=False)
         item.photo = self.get_photo()
         vendor = get1_by_property(Vendor, "name", vendor_name)
         vendor.items.append(item.put())
         vendor.put()
         self.redirect("/v/%s/item/list" % vendor_name)
     else:
         self.redirect("/v/%s/item/entry" % vendor_name)
Example #24
0
def item_detail(request, item_code):
    from forms import ItemForm

    item = get_object_or_404(Item, code=item_code)
    if request.method == "POST":
        item_form = ItemForm(instance=item, data=request.POST)
        if item_form.is_valid():
            item = item_form.save()
            return redirect(item)
    else:
        item_form = ItemForm(instance=item)

    payload = {"item": item, "item_form": item_form}
    return _render("warehouse/item/detail.html", payload, request)
Example #25
0
def update(id):
    item = db_session.query(Items).filter_by(id=id).first()
    if item:
        form = ItemForm(request.form)
        if request.method=="POST" and form.validate_on_submit():
            try:
                item.name = form.name.data,
                item.quantity = form.quantity.data,
                item.description = form.description.data,
                item.date_added = datetime.datetime.now(),
                db_session.commit()
                return redirect(url_for('success'))
            except:
                return 'There was an issue updating your item'
        return render_template('update.html',id=id, form=form)
Example #26
0
def add_item():
    form = ItemForm(request.form)
    if request.method=="POST" and form.validate_on_submit():
        try:
            item = Items(
                name=form.name.data,
                quantity=form.quantity.data,
                description=form.description.data,
                date_added=datetime.datetime.now())
            db_session.add(item)
            db_session.commit()
            return redirect(url_for('success'))
        except:
            return 'There was a problem adding an item'
    return render_template('index.html', form=form)
Example #27
0
def add_item():
    u = User.query.get(session.get('uid', 0))  # User must exist
    cats = Category.query.order_by(Category.name).all()
    form = ItemForm()
    form.category_id.choices = [(c.id, c.name) for c in cats]
    if form.validate_on_submit():
        i = Item(form.name.data, form.category_id.data, session['uid'],
                 form.description.data)
        if 'photos' in request.files:
            i.photos = get_item_photo_list(i.id)
        db.session.add(i)
        db.session.commit()
        c = i.category
        return redirect(url_for('item', category=c.slug, item=i.slug))
    return render_template('add_item.html', form=form, user=u, categories=cats)
Example #28
0
def add_item():
    form = ItemForm()
    # Only when posting
    if form.validate_on_submit():
        # Populate item for insertion
        item = Items(name=form.name.data, quantity=form.quantity.data,
                     description=form.description.data, date_added=datetime.datetime.now())
        try:
            db_session.add(item)
            db_session.commit()
            return redirect(url_for('success'))
        except:
            #When failed, pressing the back key will keep the input boxes filled
            return "Go back and check if quantity is a number or not."
    return render_template('index.html', form=form)
Example #29
0
def create_stories(request):
	if request.POST:
		for f in request.FILES.getlist('i_path'):
			print request.FILES
			form = ItemForm(request.POST, {'i_path': f})
			if form.is_valid():
				form.save()
		
		return HttpRespondeRedirect('/complete')
	else:
		form = ItemForm()
		args = {}
		args.update(csrf(request))
		args['form'] = form
		return render(request,"create_stories.html",args)
Example #30
0
def add_item():
    form = ItemForm()
    if form.validate_on_submit():
        item = Items(id=random.randint(1, 5000),
                     name=form.name.data,
                     quantity=form.quantity.data,
                     description=form.description.data,
                     date_added=datetime.datetime.now())
        db_session.add(item)
        db_session.commit()
        flash('Thank you for entering your item')
        return redirect(url_for('success'))
    # else: add some sort of error catching here

    return render_template('index.html', form=form)
Example #31
0
def item_create(request):
    if request.method == 'POST':
        form = ItemForm(request.POST)
        if form.is_valid():
            obj = form.save(commit=False)
            obj.user = request.user
            obj.save()
            return redirect('index')
    else:
        form = ItemForm()

    data = {
        'form': form,
    }
    return render_to_response('new.html', data,
                              context_instance=RequestContext(request))
Example #32
0
def shop_main():
    listForm = ListForm()
    itemForm = ItemForm()
    catForm = CategoryForm()
    prodForm = ProductForm()
    shopForm = ShopForm()

    lists = Slist.query.all()
    cats = Category.query.all()
    shops = Shop.query.all()
    prods = db.session.query(Slist.name,
                             func.count(Item.id)).join(Item).group_by(Slist.id)
    prods = dict(prods)

    return render_template('shopapp/shopapp.html',
                           units=units,
                           lists=lists,
                           listForm=listForm,
                           itemForm=itemForm,
                           catForm=catForm,
                           prodForm=prodForm,
                           shopForm=shopForm,
                           cats=cats,
                           shops=shops,
                           prods=prods)
Example #33
0
 def get_item():
     category = Category.query.all()
     category_choice = [(c.id, c.type) for c in category]
     form = ItemForm(category_choice)
     return render_template('/forms/new_item.html',
                            title='New item',
                            form=form)
Example #34
0
def create_item(request):

    if request.method == 'POST':
        item_form = ItemForm(request.POST,prefix='item_form')

        item_content_forms = []
        for lang in LANGUAGES:
            item_content_forms.append({
                'form':ItemContentForm(request.POST,prefix='item_content' + lang[0]),
                'lang':lang[0]
            })

        if item_form.is_valid():



            valid = False
            for item_content_form in item_content_forms:
                valid = item_content_form['form'].is_valid()
                if not valid:
                    break

            if valid:
                item = item_form.save(commit=False)
                if 'item_form_avatar' in request.FILES:
                    avatar_img_name = handle_uploaded_file(request.FILES['item_form_avatar'])
                    item.avatar_img_name = avatar_img_name
                item.save()
                for item_content_form in item_content_forms:
                    item_content = item_content_form['form'].save(commit=False)
                    item_content.lang = item_content_form['lang']
                    item_content.item = item
                    item_content.save()
                return redirect('newinlib:administration:items_list')
    else:
        item_form = ItemForm(prefix="item_form")
        item_content_forms = []
        for lang in LANGUAGES:
            item_content_forms.append({
                'form':ItemContentForm(prefix='item_content' + lang[0]),
                'lang':lang[0]
            })

    return render(request, 'newinlib/administration/create_item.html', {
        'item_form': item_form,
        'item_content_forms': item_content_forms,
        })
Example #35
0
def newItem():
    """
    newItem: form to add a new item
    Args:
        none
    Returns:
        return add a item and redirect to home or show form to add a new item
    """

    if 'username' not in login_session:
        return redirect('/login')
    try:
        form = ItemForm()

        form.category_id.choices = [(0, 'Select')]
        form.category_id.choices += [(category.id, category.name) for category
                                     in session.query(Categories).
                                     order_by('name')]

        print form.errors

        if form.validate_on_submit():
            title = form.title.data
            category_id = form.category_id.data
            description = form.description.data

            if (form.title.data is not None and
                    form.category_id.data is not None and
                    form.category_id.data is not '0'):

                newItem = Items(title=title,
                                description=description,
                                category_id=category_id,
                                user_id=login_session['user_id'])

                session.add(newItem)
                session.commit()
                flash("New Item Created")

            else:
                flash("Missing required information for Add")
        else:
            return render_template('newitem.html', form=form,
                                   login_session=login_session)
    except:
        flash('Error')
    return redirect(url_for('showHomepage'))
Example #36
0
def editItem(item_id):
    itemForm = ItemForm()
    item = Item.query.get(item_id)
    slist = Slist.query.get(item.slist_id)
    if itemForm.validate_on_submit():
        item.shop = itemForm.shop.data
        item.qnty=itemForm.quantity.data
        item.price=itemForm.price.data
        item.notes=itemForm.notes.data
        coupon = itemForm.coupon.data
        if (coupon == u'нет'):
            coupon = None
        item.coupon=coupon
        db.session.commit()
        return redirect(url_for('shopapp.show_list',slist=slist.name))
    else:
        return redirect(url_for('shopapp.shop_main'))
Example #37
0
def editItem(item_id):
    itemForm = ItemForm()
    item = Item.query.get(item_id)
    slist = Slist.query.get(item.slist_id)
    if itemForm.validate_on_submit():
        item.shop = itemForm.shop.data
        item.qnty = itemForm.quantity.data
        item.price = itemForm.price.data
        item.notes = itemForm.notes.data
        coupon = itemForm.coupon.data
        if (coupon == u'нет'):
            coupon = None
        item.coupon = coupon
        db.session.commit()
        return redirect(url_for('shopapp.show_list', slist=slist.name))
    else:
        return redirect(url_for('shopapp.shop_main'))
Example #38
0
def add(request):
    """Display the 'add an item' form & save the item if validation passed"""

    if request.method == 'POST':
        form = ItemForm(request.POST.copy())
        
        if form.is_valid():            
            item = form.save(commit=False)
            item.user = request.user
            item.save()
            return HttpResponseRedirect("/todo/")
    else:
        form = ItemForm()

    return render_to_response("todo/item.html", {
        'form' : form, 
    },context_instance=RequestContext(request))
Example #39
0
def item_detail(request, item_code):
    from forms import ItemForm
    item = get_object_or_404(Item, code=item_code)
    if request.method=="POST":
        item_form = ItemForm(instance=item, data=request.POST)
        if item_form.is_valid():
            item = item_form.save()
            return redirect(item)
    else:
        item_form = ItemForm(instance=item)
    
    payload={
                'item':item,
                'item_form':item_form,
                'l_m_storage_active':"active",
             }
    return _render('warehouse/item/detail.html', payload, request)
Example #40
0
def editItem(item_id, user):
    item = Item.query.filter_by(id=item_id).first_or_404()
    # Checks user owns post
    if user['user_id'] != item.created_by:
        return redirect('/')
    else:
        form = ItemForm()
        message = None
        if request.method == 'POST':
            if form.validate_on_submit():
                item.title = form.title.data
                item.description = form.description.data
                db.session.commit()
            else:
                message = "All fields are required"
        params = dict(item=item, user=user, form=form)
        return render_template('editItem.html', **params)
Example #41
0
def search():
    form = ItemForm(request.form)
    if request.method == "POST":
        items = db_session.query(Items).filter_by(name=form.name.data).all()
        return render_template('cart.html',
                               items=items,
                               description="Found %d records" % (len(items), ))
    return render_template('search.html', form=form)
Example #42
0
def item_create(request, user_pk=None):
    # NOTE: If user_pk is not None, then we're adding a surprise

    # You can't add a surprise for yourself
    if user_pk is not None and int(user_pk) == request.user.pk:
        raise Http404

    surprise = user_pk is not None

    # If it's a surprise, we need to know who the target is.
    if surprise:
        user = get_object_or_404(User, pk=user_pk)
    else:
        user = None

    if request.method == 'POST':

        if not user:
            user = request.user

        form = ItemForm(request.POST)

        if form.is_valid():
            obj = form.save(commit=False)
            obj.user = user
            obj.surprise = surprise
            obj.created_by = request.user
            obj.save()

            if surprise:
                buy = Buy.objects.create(user=request.user, item=obj)
                buy.save()
                return redirect('person-detail', obj.user.username)
            else:
                send_new_item_notification_emails.delay(obj.pk)

            return redirect('index')
    else:
        form = ItemForm()

    data = {
        'form': form,
        'current_user': user
    }
    return render(request, 'new.html', data)
Example #43
0
def item_edit(request, pk):
    item = get_object_or_404(Item, pk=pk)

    if request.method == 'POST':
        form = ItemForm(request.POST, instance=item)
        if form.is_valid():
            form.save(commit=True)
            messages.success(request, _("Saved"))
            return redirect('/')
    else:
        form = ItemForm(instance=item)

    data = {
        'form': form
    }

    return render_to_response('new.html', data,
                              context_instance=RequestContext(request))
Example #44
0
def list(request, cat_id):
    items = Item.objects.all().filter(category=cat_id)
    form = ItemForm()
    context = {
        'items': items,
        'form': form,
        'cat_id': cat_id,
    }
    return render(request, 'inventory/list.html', context)
Example #45
0
def handler(item_id):
    form = ItemForm()
    form.category_id.choices = [(c.id, c.name)
                                for c in db_session.query(Category).order_by('name')]

    if request.method == "GET":
        return show_form(form, item_id=item_id)
    elif request.method == "POST":
        return edit_item(form, item_id=item_id)
Example #46
0
def add_item(cat_id):
    form = ItemForm()
    categories = session.query(Category).all()
    category = session.query(Category).filter_by(id=cat_id).first()
    if form.validate_on_submit():
        new_item = Item(name=form.name.data,
                        description=form.description.data or "No description",
                        category_id=category.id,
                        user_id=login_session['user_id'])
        print new_item
        session.add(new_item)
        session.commit()
        flash('Item added successfully.', "flash-success")
        return redirect(url_for('category_list', cat_id=category.id))
    return render_template('add_item.html',
                           categories=categories,
                           category=category,
                           form=form)
Example #47
0
def add_to_cart(request):
    form = ItemForm(request.POST or None)
    if form.is_valid():
        cart = Cart(request)
        row = ImageItem(
            pattern=form.cleaned_data['pattern_id'],
            media=form.cleaned_data['media_option'],
            media_orientation=form.cleaned_data['media_orientation'],
            extra_text='',
            special_instructions='')
        row.save()
        cart.add(row, form.cleaned_data['media_option'].price_cents / 100, 1)
    else:
        logging.debug("Invalid form!")
        logging.debug(request)
        logging.debug(dir(request))
        # fixme: redirect to wherever we came from?
    return HttpResponseRedirect(reverse('show_cart'))
Example #48
0
def newItem():
    itemForm = ItemForm()
    if itemForm.validate_on_submit():
        product=Product.query.filter_by(name=itemForm.product_id.data).first()
        slist = Slist.query.filter_by(name=itemForm.slist_id.data).first()
        shop=itemForm.shop.data
        qnty=itemForm.quantity.data
        price=itemForm.price.data
        notes=itemForm.notes.data
        coupon = itemForm.coupon.data
        if (coupon == u'нет'):
            coupon = None
        item = Item(product=product, shop = shop, qnty=qnty, price = price, chk = False, note=notes, slist=slist, coupon=coupon)
        db.session.add(item)
        db.session.commit()
        return redirect(url_for('shopapp.show_list',slist=slist.name))
    else:
        return redirect(url_for('shopapp.shop_main'))
Example #49
0
def sell():
    item_form = ItemForm(request.form)

    if request.method == 'POST' and item_form.validate():
        product_name = item_form.data['product']
        product = db_session.query(Product).filter(
            Product.name == product_name.lower()).first()

        seller_name = item_form.data['seller']
        seller = db_session.query(User).\
            filter(User.name==seller_name.lower()).\
            filter(User.user_type=='Seller').first()

        if product and seller:
            item = Item()
            save_item(item, item_form, new=True)

            # Add child to Product parent models
            product.items.append(item)
            seller.items.append(item)
            db_session.commit()
        else:
            if not product:
                flash('No products match "{}"'.format(product_name))
            if not seller:
                flash('No sellers match "{}"'.format(seller_name))

            return redirect('/sell')

        flash('Item created successfully!')
        return redirect('/sell')

    product_results = db_session.query(Product).all()
    # product_table = ProductResults(product_results)
    # product_table.border = True

    item_results = join_item_seller(db_session).all()
    # item_table = ItemResults(item_results)
    # item_table.border = True

    return render_template('sell.html',
                           product_results=product_results,
                           item_results=item_results,
                           item_form=item_form)
Example #50
0
def editItem(category_id, item_id, item_name):
    category = checkCategory(category_id)
    item = checkItem(item_id)
    categories = session.query(Category).all()
    form = ItemForm()
    if form.validate_on_submit():
        if item.user_id != login_session['user_id']:
            flash("User not authorised to edit the item.")
            return redirect(url_for('showCatalog'))
        if request.form['name']:
            item.name = request.form['name']
        if request.form['description']:
            item.description = request.form['description']
        if request.form['price']:
            item.price = request.form['price']
        if request.form['category_id']:
            item.category_id = request.form['category_id']

        categoryName = category.name
        for itemCategory in categories:
            if itemCategory.id == item.category_id:
                categoryName = itemCategory.name

        session.add(item)
        session.commit()
        flash("Item %s edited." % item.name)
        return redirect(
            url_for(
                'showCategory',
                category_id=item.category_id,
                category_name=categoryName
                )
            )
    else:
        if request.method == 'POST':
            flash("Error while editing the item. \
                Please fill all the required fields.")
        return render_template(
            'edititem.html',
            itemCategory=category,
            item=item,
            categories=categories,
            form=form
            )
def items():
    try:
        log.info('Start reading from DB')
        i_form = ItemForm()
        s_form = SearchForm()
        item_list = db.session.query(Item).all()
        if i_form.validate_on_submit():
            new_item = Item(i_form.sku.data, i_form.title.data)
            db.session.add(new_item)
            db.session.commit()
            i_form.sku.data = ''
            i_form.title.data = ''
            item_list = db.session.query(Item).all()
            return redirect(url_for('items'))
        return render_template('items.html', i_form=i_form, s_form=s_form, item_list=item_list)
    except:
        _, ex, _ = sys.exc_info()
        log.error(ex.message)
        return render_template('items.html', i_form=i_form, s_form=s_form, item_list=item_list)
Example #52
0
def additem():
    form = ItemForm()
    if form.validate_on_submit():
        pic = 'burger.jpg'
        if form.image.data:
            print('YO!!!!!!!!! IT IS OVER HERE!!!')
            pic = save_picture(form.image.data)
        item = Item(name=form.name.data,
                    price=form.price.data,
                    description=form.description.data,
                    category=form.category.data,
                    image_file=pic)
        flash(f'New Item has been added', 'success')
        db.session.add(item)
        db.session.commit()
        print(item.image_file)
        return redirect(
            url_for('viewdashinventory', category=form.category.data))
    return render_template('additem.html', form=form)
Example #53
0
def items_new():
    form = ItemForm(request.form)
    if request.method == 'POST' and form.validate():
        if Item.query.filter(Item.name == form.name.data).first():
            data = {'nav_urls': get_urls(), 'active_url': url_for('items_new')}
            duplicate = True
            return render_template('items_edit.html',
                                   form=form,
                                   data=data,
                                   duplicate=duplicate)
        else:
            item = Item(form.name.data, form.price.data)
            item.active = form.active.data
            dbs.add(item)
            dbs.commit()
            return redirect(url_for('items'))
    else:
        data = {'nav_urls': get_urls(), 'active_url': url_for('items_new')}
        return render_template('items_edit.html', form=form, data=data)
Example #54
0
def create_item():
    form = ItemForm()
    form.category.choices = [(b.id, b.name)
                             for b in Category.query.order_by("name")]

    if form.validate_on_submit():
        category = Category.query.filter_by(id=form.category.data).first()
        name = form.name.data
        description = form.description.data

        item = Item(name=name,
                    description=description,
                    user=g.user,
                    category=category)
        db.session.add(item)
        db.session.commit()
        return redirect(url_for('user.profile'))

    return render_template("items/newitem.html", form=form)
Example #55
0
def add_to_cart(request):
	form = ItemForm(request.POST or None)
	if form.is_valid():
		cart = Cart(request)
		row = ImageItem(
			pattern=form.cleaned_data['pattern_id'],
			media=form.cleaned_data['media_option'],
			media_orientation=form.cleaned_data['media_orientation'],
			extra_text='',
			special_instructions=''
			)
		row.save()
		cart.add(row, form.cleaned_data['media_option'].price_cents / 100, 1)
	else:
		logging.debug("Invalid form!")
		logging.debug(request)
		logging.debug(dir(request))
		# fixme: redirect to wherever we came from?
	return HttpResponseRedirect(reverse('show_cart'))
Example #56
0
def add():
    global db

    form = ItemForm(request.form)

    if request.method == 'POST' and form.validate():
        document = {}
        for field, value in request.form.items():
            document[field] = value

        if 'title' in document and 'media_type' in document:
            slug = common.slugify(document['title'])
            document['slug'] = slug
            db.save(document)
            print "Document saved."
            flash('Changes saved.')
            return redirect(url_for('edit', slug=slug))
    types = [item[0] for item in MEDIA_TYPES]
    return render_template('form.html', title="Add item", form=form, types=types, document={})
Example #57
0
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)
Example #58
0
def update(id):
    form = ItemForm()
    to_change = db_session.query(Items).filter_by(id=id).first()
    if form.validate_on_submit():
        try:
            for k in to_change.__dict__.keys():
                if k is 'date_added':
                    to_change.date_added = datetime.datetime.now()
                elif k is '_sa_instance_state':
                    pass
                elif k is 'id':
                    pass
                else:
                    # Appending keys to variables break syntax
                    setattr(to_change, k, getattr(form,k).data)
            db_session.commit()
            return redirect(url_for('success'))
        except:
            return "Update failed. Try again."
    return render_template('update.html', form=form)
Example #59
0
def pattern_page(request, pattern_id):
    pattern = get_object_or_404(Pattern, pk=pattern_id)
    return {
        'pattern': pattern,
        'scale': findImageScaling(pattern.pixel_width, pattern.pixel_height),
        'media': Media.objects.all(),
        'breadcrumbs': [[{
            'url': '/',
            'text': 'Home'
        }]],
        'carthelper': ItemForm(pattern_id=pattern_id),
    }
Example #60
0
def newItem(user):
    error = None
    form = ItemForm()
    if request.method == 'POST':
        if form.validate_on_submit():
            if Item.query.filter_by(title=form.title.data).first():
                error = 'Item is already in our records'
            else:
                item = Item(title=form.title.data,
                            description=form.description.data,
                            cat_name=form.cat_name.data,
                            created_by=user['user_id'])
                db.session.add(item)
                db.session.commit()
                # Adds new entry to Algolia's index
                algolia_index.add_objects([item.serialize])
                redirect(url_for('index'))
        else:
            error = 'All fields are required'
    params = dict(user=user, form=form, error=error)
    return render_template('newItem.html', **params)