예제 #1
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)
예제 #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. It might take a half hour to reflect the proper search results."))
            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))
예제 #3
0
파일: views.py 프로젝트: 1john/greenbox
def item(request, item_id=None):  #add/edit item object
    if Team.objects.filter(user=request.user).exists():
        team = Team.objects.get(user=request.user)

    else:
        return HttpResponseRedirect('/team')

    args = {}
    if item_id:
        item = Item.objects.get(id=item_id)
        args.update({'item': item})
    else:
        item = None

    if request.method == 'POST':
        form = ItemForm(request.POST, instance=item)
        if form.is_valid():
            item = form.save(commit=False)
            item.thumbnail = 'https://%s.s3.amazonaws.com/%s' % (
                os.environ.get('S3_BUCKET_RESIZED'),
                item.img_url.split('/').pop())

            item.team = team
            item.save()
            return HttpResponseRedirect('/dashboard')
    else:
        form = ItemForm(instance=item)

    args.update({'team': team})
    args.update({'form': form})
    #args.update(csrf(request))
    return render(request, 'templates/showcase/item.html', args)
예제 #4
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))
예제 #5
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)
예제 #6
0
def create_new_item(request, proceeding_id):
    context = {}
    if request.method == 'POST':
        form = ItemForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(
                reverse('items', kwargs={'proceeding_id': proceeding_id}))
    else:
        form = ItemForm()
        context['form'] = form
        return render_to_response('new_item.html', context)
예제 #7
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)
예제 #8
0
파일: views.py 프로젝트: Kirito1899/libcms
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,
    })
예제 #9
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)
예제 #10
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)
예제 #11
0
def item(id):
    form = ItemForm()
    # item = Item.query.filter_by(id = id).first()
    item = Item.query.filter_by(id=id).first()
    print(item.image_file)
    if request.method == 'POST':
        if form.validate_on_submit():
            pic = item.image_file
            print(pic)
            if form.image.data:
                print('There is a picture in the form')
                pic = save_picture(form.image.data)
            print('Form has validated successfully')
            print(form.price.data)
            print(item)
            item.name = form.name.data
            item.price = form.price.data
            item.description = form.description.data
            item.image_file = pic
            db.session.commit()
            print(item.name)
            return redirect(
                url_for('viewdashinventory', category=form.category.data))
    if request.method == 'GET':
        form.name.data = item.name
        form.price.data = item.price
        form.description.data = item.description
    return render_template('item.html', item=item, form=form)
예제 #12
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'))
예제 #13
0
def add_item():
    form = ItemForm()
    if form.validate_on_submit():
        #Through testing, I found this bit of code is what's causing the 504 error.
        #Took out the date_added variable to see if that was holding it up.
        #Added datetime back in. It didn't break anything. Still getting outputs like [,,].

        item = Items(name=form.name.data,
                     quantity=form.quantity.data,
                     description=form.description.data,
                     date_added=datetime.datetime.now())

        ##        #Maybe item isn't being populated correctly. Try one attribute at a time.
        ##        #Still getting the same [,,,] type output.
        ##        item = Items()
        ##        item.name = form.name.data
        ##        item.quantity = form.quantity.data
        ##        item.description = form.description.data
        ##        item.date_added = datetime.datetime.now()

        #More testing shows the error 504 came from calling db_session.
        #This was because the postgres port was supposed to stay as 5432.
        #Output after submittion is a list of commas, so maybe item isn't getting
        #added correctly to the table.
        db_session.add(item)
        db_session.commit()
        return redirect(url_for('success'))
    return render_template('index.html', form=form)
예제 #14
0
def item_add(type=0):
    # 商品/服务添加
    form = ItemForm(type=type)
    if form.validate_on_submit():
        # 不对名称做校验了
        #if Item.query.filter_by(name=form.name.data, type=type).first():
        #    flash(u'您输入的名称已存在', 'err')
        #    return redirect(url_for('admin.item_add', type=type))
        item = Item(
            name=form.name.data,
            cate=form.cate.data,
            type=type,
            salesprice=float(form.salesprice.data),
            rewardprice=float(form.rewardprice.data),
            costprice=float(form.costprice.data),
            unit=form.unit.data,
            standard=form.standard.data,
            valid=form.valid.data,
            remarks=form.remarks.data,
        )
        oplog = Oplog(user_id=session['user_id'],
                      ip=request.remote_addr,
                      reason=u'添加商品/服务项目:%s' % form.name.data)
        objects = [item, oplog]
        db.session.add_all(objects)
        db.session.commit()
        flash(u'添加成功', 'ok')
        return redirect(url_for('admin.item_add', type=type))
    return render_template('admin/item_add.html', form=form, type=type)
예제 #15
0
def additem():
    """
    this allow users to add items
    """
    form = ItemForm(request.form)
    categories = Category.query.all()
    form.category.choices = [(c.id, c.name) for c in categories]
    if request.method == 'POST' and form.validate():
        print('\n\n\n\ninside post')
        name = form.name.data
        price = form.price.data
        brand = form.brand.data
        description = form.description.data
        category = form.category.data
        image = form.image.data
        print(name, price, description, image, brand, category)
        item = Item(name=name,
                    price=price,
                    description=description,
                    image=image,
                    brand=brand,
                    category_id=category,
                    user_id=login_session['gplus_id'])
        db.session.add(item)
        db.session.commit()
        flash('item saved successfully', 'success')
        return redirect('/')
    elif form.errors:
        flash(form.errors, 'danger')
        return redirect('/')
    else:
        print('\n\n\n\ninside get')
        return render_template('additem.html', form=form)
예제 #16
0
def addItem(name):
    """Add an item to a named category or render a form.

    Args: A category name

    Returns: Add an item or render a form.
    """
    # Store named category and the logged in user
    category = Category.query.filter_by(name=name).first_or_404()
    user = Users.query.filter_by(id=login_session['users_id']).first_or_404()
    # Verify that the logged in user is creator or admin
    if category.users_id != login_session['users_id'] and not user.admin:
        flash(' You are not authorized add items to that category.')
        return redirect(url_for('category.showCategory', name=name))
    # Initiate the form.
    form = ItemForm()
    # On POST of a valid form, add the new item.
    if form.validate_on_submit():
        item = Item(form.name.data, form.description.data,
                    form.amazon_asin.data, form.picture.data, category.id,
                    login_session['users_id'])
        # Check if there is a amazon url, and if so extract asin
        if form.amazon_url.data is not None:
            asin = re.search("[A-Z0-9]{10}", form.amazon_url.data)
            if asin:
                item.amazon_asin = asin.group(0)
        db.session.add(item)
        db.session.commit()
        flash('New Item %s Successfully Created' % item.name)
        # Log new item
        current_app.logger.info('New Item %s Created on %s' %
                                (item.name, str(item.dateCreated)))
        return redirect(url_for('category.showHome'))
    else:
        return render_template('newItem.html', form=form, category=category)
예제 #17
0
def item_new():
    form = ItemForm(request.form)
    form.category_id.choices = [(cat.id, cat.name) for cat in categories]
    if request.method == 'POST' and form.validate():
        return item_new_post(form)
    else:
        return item_new_get(form)
예제 #18
0
def newItem(category_id, category_name):
    category = checkCategory(category_id)
    form = ItemForm()
    if form.validate_on_submit():
        newItem = Item(
            name=request.form['name'],
            description=request.form['description'],
            price=request.form['price'],
            category_id=category.id,
            user_id=login_session['user_id'])
        session.add(newItem)
        session.commit()
        flash("Item %s created" % newItem.name)
        return redirect(
            url_for(
                'showCategory',
                category_id=category.id,
                category_name=category.name
                )
            )
    else:
        if request.method == 'POST':
            flash("Error while creating the item. \
                Please fill all the required fields.")
        return render_template(
            'newitem.html', category=category, form=form)
예제 #19
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
예제 #20
0
def wwIndex():
    global counter
    lock=Lock()
    with lock:
        counter+=1
        print (counter)
    form=ItemForm()
    itemsOfInterest = Item.query()
    if len(itemsOfInterest.fetch(None))==0:
        mower=Item(id=str(uuid.uuid1()), item='Lawn Mowers')
        eater=Item(id=str(uuid.uuid1()),item='Weed Eaters')
        mower.addModel('Honda')
        mower.addModel('Black & Decker')
        eater.addModel('Torro')
        eater.addModel('Echo')
        print mower.item
        print eater.item
        mower.put()
        eater.put()
        itemsOfInterest = Item.query()
    print "The query length is "+str(len(itemsOfInterest.fetch(None)))
    if form.validate_on_submit():
        newItem = Item(id=str(uuid.uuid1()),item=form.item.data)
        print("myUUID is "+newItem.id)
        newItem.put()
        flash('New item added!')
        return redirect(url_for('index'))
    return render_template('index.html',
                           title='USI Help System',
                           itemsOfInterest=itemsOfInterest,
                           form=form
                           )
예제 #21
0
def add_item():
    form = ItemForm()
    if form.validate_on_submit():
        try:
            _ = int(form.quantity.data)
        except ValueError:
            return "The \"quantity\" field must contain an integer. No items were added, and the database was NOT updated."

        if (len(form.name.data) > 256):
            _l = "name"
        elif (len(form.description.data) > 256):
            _l = "description"
        else:
            _l = "x"

        if (_l != "x"):
            return "Length of the \"{}\" field must not exceed 256 characters. No items were added, and the database was NOT updated.".format(
                _l)

        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)
예제 #22
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)
예제 #23
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)
예제 #24
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)
예제 #25
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)
예제 #26
0
def item_edit(item_id):
    item = session.query(Item).filter_by(id=item_id).one()
    form = ItemForm(request.form, item)
    form.category_id.choices = [(cat.id, cat.name) for cat in categories]
    if request.method == 'POST' and form.validate():
        return item_edit_post(form, item)
    else:
        return item_edit_get(form, item)
예제 #27
0
파일: views.py 프로젝트: tdhunt631/cs4990
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)
예제 #28
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)
예제 #29
0
def itemAdd(request):
    if request.method == 'POST':
        form = ItemForm(request.POST, None)
        if form.is_valid():
            item = form.save(commit=False)
            item.title = form.cleaned_data['title']
            item.description = form.cleaned_data['description']
            item.save()
            return HttpResponse('OK')
        else:
            error_dict = {}
            for error in form.errors:
                error_dict[error] = form.errors[error]

            return HttpResponseBadRequest(json.dumps(error_dict))
    else:
        form = ItemForm()
        return render(request, 'item_add_partial.html', {'form': form})
예제 #30
0
def items_list():
    form = ItemForm()
    error = ""
    if request.method == "POST":
        if form.validate_on_submit():
            items.create((tuple(form.data.values())[:4]))
    return render_template("items.html",
                           form=form,
                           items=items.all(),
                           error=error)  # noqa