def add(request): if not request.session.get('is_login', None): return redirect('/login/') if request.method == 'POST': username = request.session.get('user_name', None) phone = request.POST['phone'] title = request.POST['title'] price = request.POST['price'] if price == '': message = "请填写价格" return render(request, 'market/add.html', locals()) # noinspection PyBroadException try: img = request.FILES['img'] except: message = "请上传图片" return render(request, 'market/add.html', locals()) image = Image.open(img) width, height = image.size rate = 1.0 if width >= 2000 or height >= 2000: rate = 0.3 elif width >= 1000 or height >= 1000: rate = 0.5 elif width >= 500 or height >= 500: rate = 0.9 width = int(width * rate) height = int(height * rate) image.thumbnail((width, height), Image.ANTIALIAS) pic_io = BytesIO() image.save(pic_io, image.format) pic_file = InMemoryUploadedFile(file=pic_io, field_name=None, name=img.name, content_type=img.content_type, size=img.size, charset=None) cate = request.POST['cate'] describe = request.POST['describe'] new_goods = Goods(username=username, phone=phone, title=title, price=price, img=pic_file, cate=cate, describe=describe) new_goods.save() return redirect('/') message = "上传图片有点慢,图片上传成功会自动跳转" return render(request, 'market/add.html', locals())
def add_goods(request): user = request.user user_profile = UserProfile.objects.get(user=user) category_list = Category.objects.all() if request.method == 'POST': user_profile.recent_nums += 1 user_profile.nums += 1 if user_profile.recent_nums > 6: return render(request, 'add_fail.html', {'user': user_profile}) name = request.POST.get('name') trade_location = request.POST.get('trade_location') price = request.POST.get('price') description = request.POST.get('description') category = request.POST.get('category') typ_id = int(request.POST.get('typ_id')) if name and trade_location and price and description: new_goods = Goods(name=name, trade_location=trade_location, price=price, description=description, typ=typ_id) new_goods.category = Category.objects.get(name=category) new_goods.seller = user_profile if 'picture' in request.FILES: name = str(request.FILES['picture']) ext = os.path.splitext(name)[1] print(ext) path = str(user.username) + '-' + str(user_profile.nums) + ext t_x = int(request.POST.get('dataX')) t_y = int(request.POST.get('dataY')) t_width = int(request.POST.get('dataWidth')) t_height = int(request.POST.get('dataHeight')) t_rotate = int(request.POST.get('dataRotate')) fname = os.path.join(settings.MEDIA_ROOT, path) img = Image.open(request.FILES['picture']) crop_im = img.rotate(-t_rotate, expand=True).crop( (t_x, t_y, t_x + t_width, t_y + t_height)).resize( (600, 600), Image.ANTIALIAS) crop_im.save(fname, quality=100, dpi=(600, 600)) new_goods.picture = path new_goods.save() user_profile.save() return HttpResponseRedirect('/goods' + '/' + str(typ_id)) return render(request, 'add_goods-1.html', { 'user': user_profile, 'category_list': category_list })