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 edit_item(request, item_id): ''' 1、修改的记录id是item_id 2、获取该记录 3、使用提交的数据更新该记录 ''' other_error = "" try: modify_item = Item.objects.get(id=item_id) except Item.DoesNotExist: pass else: if request.method == 'POST' and request.is_ajax(): form = ItemForm(request, data=request.POST.copy()) # 使用提交的数据构建表单 if form.is_valid(): # 如果数据格式正确 clean_data = form.cleaned_data # 验证过的数据 c_id = int(clean_data['category']) try: category = Category.objects.get(id=c_id) # 分类不存在将抛出异常 except Category.DoesNotExist: form.add_error('category', '该分类已经不存在') else: modify_item.pub_date = clean_data['pub_date'] modify_item.category = category modify_item.price = clean_data['price'] modify_item.comment = clean_data['comment'] try: modify_item.save() except Exception: other_error = "修改保存时发生异常" else: print('Item修改成功') in_json = json.dumps([True, {}]) # 返回成功操作的结果 return HttpResponse(in_json, content_type='application/json') else: in_json = json.dumps([False, form.errors]) # 返回错误操作的结果 return HttpResponse( in_json, content_type='application/json') # 表单验证不通过,返回错误信息 else: # 构建待修改账单的表单 pub_date = modify_item.pub_date category = modify_item.category.id price = modify_item.price comment = modify_item.comment form = ItemForm(request, data={ 'pub_date': pub_date, 'category': category, 'price': price, 'comment': comment }) return render(request, 'jizhang/new_item.html', { 'form': form, 'other_error': other_error })