Django新手开发竞价系统遇view返回None及出价不生效问题
问题排查与修复方案
问题1:点击Place Bid按钮出价未提交
根因如下:
- 变量
price定义位置错误:当前仅当拍品已关闭(listing.activate=True)时才会定义price,但正常竞价开放状态(listing.activate=False)下price未定义,导致后续出价校验逻辑失效 - 出价校验逻辑错误:仅对比了起拍价
listing.price,未对比当前最高出价 - 模型字段赋值错误:出价成功后尝试给
listing.bid赋值,但Post模型不存在bid字段,应该更新currentBid字段 - 模板路径拼写错误:表单校验失败时返回的模板路径写为
acutions/item.html,少了字母a,应为auctions/item.html - 未区分GET/POST请求:所有请求共用一套逻辑,GET请求下也会触发POST相关的校验逻辑
问题2:点击关闭竞价按钮抛ValueError
根因如下:
- 处理关闭竞价逻辑后未做重定向,部分分支场景下视图未返回HttpResponse对象
- 错误提示中提到的
bidding视图与你贴出的viewList视图不匹配,需检查urls.py中路由配置是否正确,确保关闭竞价的请求指向正确的视图函数
修复后的完整views.py代码
from django.shortcuts import get_object_or_404, redirect def viewList(request, id): listing = get_object_or_404(Post, id=id) # 替换原来的User.objects.get,避免未登录时报错 user = request.user is_watched = False if user.is_authenticated: is_watched = listing.watchers.filter(id=user.id).exists() # 仅处理POST请求 if request.method == "POST": # 处理关闭竞价逻辑 if request.POST.get('button') == "Close" and user == listing.creator and not listing.activate: listing.activate = True listing.save() return redirect('viewList', id=id) # 处理出价逻辑 if request.POST.get('button') == "Place Bid" and not listing.activate and user != listing.creator: form = BidForm(request.POST) if form.is_valid(): bid = form.save(commit=False) bid.user = user bid.save() listing.bids.add(bid) # 更新当前最高出价 listing.currentBid = bid.bid listing.save() return redirect('viewList', id=id) else: # 校验失败返回错误 return render(request, 'auctions/item.html', { "listing": listing, 'form': form, "message": "Error! Your bid must be larger than the current highest bid!", 'comment_form': CommentForm(), 'comments': listing.get_comments.all(), 'is_watched': is_watched, }) # GET请求统一返回上下文 context = { 'listing': listing, 'comment_form': CommentForm(), 'comments': listing.get_comments.all(), 'is_watched': is_watched, 'form': BidForm() } return render(request, 'auctions/item.html', context)
其他需调整的细节
- 修改模板中出价提示,展示当前最高出价而非起拍价,在原有起拍价展示行下方补充:
<li class="list-group-item mb-2"><h5>Current highest bid: {{listing.currentBid|default:listing.price}}$</h5></li> - 检查
BidForm的字段配置,确保表单字段对应Bid模型的bid字段,没有额外多余字段
内容的提问来源于stack exchange,提问作者wajd
相关产品推荐
相关产品推荐

