本文整理汇总了Python中forms.ItemForm类的典型用法代码示例。如果您正苦于以下问题:Python ItemForm类的具体用法?Python ItemForm怎么用?Python ItemForm使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ItemForm类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: createItem
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)
示例2: item_add
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))
示例3: post_item
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))
示例4: items_edit
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)
示例5: add_item
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
示例6: add_item
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)
示例7: item_add_typed
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)
示例8: item_edit
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)
示例9: UpdateItem
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)
示例10: item_add_edit
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})
示例11: item_store
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")
示例12: update_item
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)
示例13: item_form
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,
})
示例14: post
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)
示例15: item_detail
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)