def save(self, id=None): new_item = Item(price=self.cleaned_data['price'], category=self.cleaned_data['category'], pub_date=self.cleaned_data['pub_date'], comment=self.cleaned_data['comment'], id=id) new_item.save()
def test_data(): pwd = '123456' name1 = 'xiaoming' name2 = 'xiaohong' u1 = User.objects.filter(username=name1) u2 = User.objects.filter(username=name2) u1 = u1 if u1.exists() else User.objects.create_user(username=name1, password=pwd) u2 = u2 if u2.exists() else User.objects.create_user(username=name2, password=pwd) u_list = User.objects.filter(username__contains='xiao') print(u_list) for u in u_list: c1 = Category(name='salary', isIncome=True, p_category=None, user=u) c1.save() c2 = Category(name='salary_lp', isIncome=True, p_category=c1, user=u) c2.save() base_salary = 1000 if u.username == 'xiaoming' else 2000 for i in range(10): price = base_salary * (1.0 + i / 10.0) i = Item(price=price, category=c2, pub_date='2017-%d-01' % (i + 1), comment='工资') i.save() print("测试数据创建成功")
def new_item(request): other_error = '' if request.method == 'POST' and request.is_ajax(): print(request.POST) form = ItemForm(request, data=request.POST.copy()) # 提交的数据构建该用户的表单对象 if form.is_valid(): # 数据经过基本验证 clean_data = form.cleaned_data # 验证过的数据 try: category = Category.objects.get(id=int( clean_data['category'])) # 从数据库中获取该分类 except Category.DoesNotExist: form.add_error('category', '该分类已经不存在') # 某些异常 else: pub_date = clean_data['pub_date'] price = clean_data['price'] comment = clean_data['comment'] new_item = Item(pub_date=pub_date, category=category, price=price, comment=comment) # 通过Item模型将数据保存到数据库 new_item.save() print('Item创建成功') in_json = json.dumps([True, {}]) # 返回操作状态,成功 return HttpResponse(in_json, content_type='application/json') in_json = json.dumps([False, form.errors]) # 错误 return HttpResponse(in_json, content_type='application/json') # 表单验证不通过,返回错误信息 else: form = ItemForm(request) return render(request, "jizhang/new_item.html", { 'form': form, 'other_error': other_error })
def create_items(): pwd = '123456' name = 'xiaoming' try: user = User.objects.get(username=name) except User.DoesNotExist: user = User.objects.create_user(username=name, password=pwd) # c = Category.objects.get(user=user, name='salary') base_salary = 1000 for i in range(100): price = base_salary * (1 + i / 10.0) i = Item(price=price, category=c, pub_date='2{:03}-01-01'.format(i), comment='工资%d' % i) i.save() print("测试数据创建成功")