def docs_in_add_item(request, document_id): document = get_object_or_404(Document, pk=document_id, doc_type=0) if request.method == "POST": form = ItemForm(request.POST) if form.is_valid(): # найдем такой же груз items = Item.objects.filter( factory_number=form.cleaned_data["factory_number"]) if items.exists(): # пока берем первый, но вообще единица должна быть уникальной item = items.first() else: item = Item( name=form.cleaned_data["name"], factory_number=form.cleaned_data["factory_number"], passport_number=form.cleaned_data["passport_number"], weight=form.cleaned_data["weight"], ) item.save() entry = ItemEntry(description=form.cleaned_data["description"], item=item, operation=document.operation) entry.save() return HttpResponseRedirect( reverse('main:docs_in_edit', args=(document.pk, )))
def get_items_booked_by_user(code, n_latest): items = Booking.objects \ .filter(hh_user__pk=code) \ .values('item', 'item__name', 'item__uri', 'item__image_uri') \ .annotate(max_dt=Max('dt')) \ .order_by('-max_dt')[:n_latest] return [ Item(code=item["item"], name=item["item__name"], uri=item["item__uri"], image_uri=item["item__image_uri"]).as_dict() for item in items ]
def register(user_id): login_user_check(user_id) if request.method == "POST": user_id = user_id item_name = request.form.get('item_name') url = request.form.get('url') price = get_price(url) if price is None: flash("商品価格の取得に失敗しました。もう一度お試しください。", "info") return redirect(url_for("item.register", user_id=user_id)) latest_price = price lowest_price = price if item_name: item = Item(user_id, item_name, url, latest_price, lowest_price) db.session.add(item) db.session.commit() p = Price(item.id, price) db.session.add(p) db.session.commit() draw_graph(item.id) return redirect(url_for('user.mypage', user_id=user_id)) else: return redirect(url_for("item.register", user_id=user_id)) return render_template("item_register.html", user_id=user_id)
def createItemFromData(soup, restaurant): name = soup.find('dd').text name = name.replace('®', '') name = name.replace('©', '') type_of_item = 'meal' for dd in soup.find_all('dd'): if 'fl oz' in dd.text: floz = int(dd.text.split(' ')[-3]) type_of_item = 'drink' for metric in dd.find_all('li'): if "Calories " in metric.text: calories = int(metric.text.split(' ')[-1]) elif "Total Fat" in metric.text: total_fat = Decimal(metric.text.split(' ')[-1].strip('g')) elif "Saturated Fat" in metric.text: sat_fat = Decimal(metric.text.split(' ')[-1].strip('g')) elif "Trans Fat" in metric.text: trans_fat = Decimal(metric.text.split(' ')[-1].strip('g')) elif "Cholesterol" in metric.text: cholesterol = Decimal(metric.text.split(' ')[-1].strip('mg')) elif "Sodium" in metric.text: sodium = Decimal(metric.text.split(' ')[-1].strip('mg')) elif "Carbohydrates" in metric.text: carbs = Decimal(metric.text.split(' ')[-1].strip('g')) elif "Fiber" in metric.text: fiber = Decimal(metric.text.split(' ')[-1].strip('g')) elif "Sugar" in metric.text: sugar = Decimal(metric.text.split(' ')[-1].strip('g')) elif "Protein" in metric.text: protein = Decimal(metric.text.split(' ')[-1].strip('g')) item = Item(name=name, restaurant=restaurant, type_of_item=type_of_item, calories=calories, protein=protein, carbs=carbs, total_fat=total_fat, sat_fat=sat_fat, trans_fat=trans_fat, cholesterol=cholesterol, sodium=sodium, sugar=sugar, fiber=fiber, floz=floz if type_of_item == 'drink' else 0) print(f"Name: {item.name}") print(f"Restaurant: {item.restaurant}") print(f"Type Of Item: {item.type_of_item}") print(f"Calories: {item.calories}") print(f"Protein: {item.protein}") print(f"Carbs: {item.carbs}") print(f"Total Fat: {item.total_fat}") print(f"Saturated Fat: {item.sat_fat}") print(f"Trans Fat: {item.trans_fat}") print(f"Cholesterol: {item.cholesterol}") print(f"Sodium: {item.sodium}") print(f"Sugar: {item.sugar}") print(f"Fiber: {item.fiber}") print(f"Fl Oz: {item.floz}") print('-' * 40) item.save() print("O" * 50) print("Saved Item to Database") print("O" * 50) return item
def test_item_model_has_required_fields(self): item = Item() self.assertRaises(IntegrityError, item.save)
def item(request): """ * get itn:item_num每次取得贴子条数 st:start_pos:开始条数 cat:catalog :分类 tag:拼音缩写 JY ZH PC XK XR TC todo 管理员自定义 # todo :缓存 #todo 用户id查询 #todo 用户id ps :删除在post的基础上op=DELETE *post """ res = "" op = request.POST.get("op", None) if request.method == "GET": item_num = request.GET.get('itn', 10) start_pos = request.GET.get("st", None) catalog = request.GET.get("tag", "all") # TODO page = request.GET.get("pg", 1) # 上拉刷新 if start_pos is None: select_obj = Item.objects.all() start_pos = Item.objects.order_by('-pk').first().id # 下拉刷新,前端自动返回启刷的id else: # 只搜索id值小于起始点的 select_obj = Item.objects.filter(pk__lte=start_pos) # 图片请求令启一个api,减轻服务器压力 select_obj = select_obj.order_by('-pk').values() paginator = Paginator(select_obj, item_num) try: content = paginator.page(page) except PageNotAnInteger as e: content = paginator.page(1) print(e) # todo 改log except EmptyPage as e: # 是invalid的子类要放在前面 #todo 前端要判断最后一页到了没,到了就不能在页面加载最后一页了 content = paginator.page(paginator.num_pages) print(e) except InvalidPage as e: content = paginator.page(1) print(e) # todo 改log # for per_item in content: # if() # content=serializers.serialize("json", content, ensure_ascii=False) content = list(content) data = { 'mag': 'ok', 'status': 200, 'per_page': int(paginator.per_page), 'num_page': int(paginator.num_pages), 'start_pos': start_pos, "page_now": page, 'content': content } return JsonResponse(data) # end if ########### # 发帖 elif request.method == "POST" and op is None: i_title = request.POST.get('ttl', False) i_content = request.POST.get('cnt', False) # 内容 i_tag = request.POST.get('tag', False) # 标签 i_p_id = request.POST.get('p_id', False) # 发帖人id #todo 身份验证 i_id = request.POST.get('i_id', False) if i_title and i_tag and i_content and i_p_id: dict_to_add = { 'i_title': i_title, 'i_content': i_content, 'i_tag': i_tag, 'i_p_id': i_p_id } try: if not i_id: it = Item(**dict_to_add) it.save() msg = 'add_success' else: it = Item.objects.filter(pk=i_id) it.update(**dict_to_add) # 创建并写入数据库 msg = 'update_success' # 先储存否则外码设置有问题 # todo 图片修改? if request.FILES: image_list = request.FILES.getlist("img") for image in image_list: img = Image(file=image, item=it) img.save() return JsonResponse({"msg": msg, 'status': 200}) except Exception as e: res = str(e) else: res = "missing argument" elif request.method == "POST" and op == "DELETE": i_p_id = request.POST.get('p_id', False) # 发帖人id #todo 身份验证 i_id = request.POST.get('i_id', False) # todo 无法访问 if not Item.objects.filter(pk=i_id).exists(): res = "not found" else: the_item = Item.objects.filter(pk=i_id).first() print(the_item) print(i_p_id) print(i_id) print(the_item.i_p_id) if not i_p_id or the_item.i_p_id != i_p_id: res = "no access to delete" else: the_item.delete() return JsonResponse({"msg": 'delete_success', 'status': 200}) return JsonResponse({"msg": 'illegal operation::' + res, "status": 400})
def handle(self, *args, **options): restaurant_count = options["count"] # keep track of used names, streets etc. in the variables below, # so we can prevent duplicates names = [] streets = [] cities = [] # XXX factorize into smaller functions for item in range(restaurant_count): print "generate restaurant %d" % (item + 1) r = Restaurant() r.name = gen_unique_name(names, restaurant_names) r.save() print "generate address" a = Address(country=random.choice(_countries)) a.street = gen_unique_name(streets, street_names) a.street_no = random.randint(1, 100) a.zip = random.randint(1000, 100000) a.city = gen_unique_name(cities, city_names) a.restaurant = r a.save() count = random.randint(5, 25) print "generate %d tables" % count for i in range(1, 1 + count): t = Table() t.restaurant = r t.no = i t.save() print "add supported payment methods" for _ in range(2, len(_payment_methods)): method = random.choice(_payment_methods) if method not in r.payment_method.all(): r.payment_method.add(method) r.save() print "generate menu" m = Menu() m.currency = random.choice(_currencies) m.language = _languages[2] m.restaurant = r m.save() m.translations.add(_languages[0]) m.translations.add(_languages[1]) m.save() items = [] _cat_names = [] count = random.randint(3, 12) itemid = 1 print "generate %d categories" % count for j in range(1, 1 + count): c = Category() c.menu = m c.ordering = j c.view = random.choice(_views) c.save() count = random.randint(4, 20) # i18n stuff name = gen_unique_name(_cat_names, category_names) for lang in _languages: c18n = CategoryI18n() c18n.category = c c18n.language = lang c18n.name = name if lang.abbr != "en": c18n.name += "(%s)" % lang.abbr c18n.save() print "generate %d items" % count for _ in range(1, count): item = Item() item.no = itemid itemid += 1 item.category = c item.price = "%.2f" % random.uniform( 1, 110) # 2 decimal points item.save() item.image.save("item%d.jpg" % item.id, random.choice(_pictures), save=True) count = random.randint(0, 8) # "assign %d allergens" % count for k in range(count): a = random.choice(_allergens).allergen if a in ItemAllergen.objects.filter(item=item, allergen=a): continue traces = bool(random.randint(0, 1)) ItemAllergen.objects.get_or_create( item=item, allergen=a, traces=traces)[0].save() item.save() # i18n stuff name = gen_unique_name(items, food_names) for lang in _languages: i18n = ItemI18n() i18n.item = item i18n.language = lang i18n.name = name if lang.abbr != "en": i18n.name += "(%s)" % lang.abbr i18n.description = "Very delicious %s. It is made with love and all the care it is needed to make a great %s." % ( name, name) i18n.save() print self.stdout.write('Successfully added %d restaurants' % restaurant_count)
from main.models import User, Item base_name = "你好世界" for i in range(10): tt = User(u_name=base_name + str(i), u_pwd="123445") tt.save() Item(i_title=base_name + str(i), i_content=base_name + str(i), i_p_id=tt).save()