商品竞价关闭按钮功能异常及显示权限问题求助
商品竞价关闭按钮功能异常及显示权限问题求助
Hey 朋友,我看你在做商品竞价的关闭功能时遇到了几个头疼的问题:按钮对所有人可见、点击毫无反应,还有后端逻辑的小bug。我帮你逐个拆解,一步步修复~
一、先解决最直观的:按钮点击没反应
你在模板里写的按钮是 <button type="button">,这种类型的按钮只会触发前端JS事件,根本不会提交表单到后端。要让它触发POST请求,把按钮类型改成 submit 就行:
<button type="submit" class="btn btn-danger">Close</button>
二、控制按钮的显示权限:只给卖家看
现在按钮谁都能看到,我们得加个判断:只有登录用户是当前商品的卖家时,才显示关闭按钮(同时还要确保商品还没被关闭)。修改模板里的逻辑:
{% if user.is_authenticated and user == product.user %} {% if product.active_bool and bid_info.checkclose %} <p>This is close!</p> {% else %} <form method="post" action="{% url "close_bid" product.id %}"> {% csrf_token %} <button type="submit" class="btn btn-danger">Close</button> </form> {% endif %} {% else %} {% if product.active_bool and bid_info.checkclose %} <p>This is close!</p> {% endif %} {% endif %}
⚠️ 注意:模板里直接写 Bid_info.checkclose 是错的,得用具体的实例对象。你需要在渲染商品详情页的视图里,把对应商品的 bid_info 传到模板上下文,比如:
# 假设这是渲染page_product的视图 def page_product(request, product_id): product = get_object_or_404(Product, id=product_id) bid_info = get_object_or_404(Bid_info, product=product) return render(request, 'page_product.html', {'product': product, 'bid_info': bid_info})
三、修复后端视图的逻辑错误
你的 close_bid 视图有几个关键bug,导致权限判断失效、修改不生效:
- 卖家身份判断错误:
user.id == ProductForm.user.id完全不对,ProductForm是表单类,不是当前商品的实例,应该直接用已获取的product对象的user:user == product.user - Bid_info查询错误:用
pk=product_id查Bid_info是错的,因为Bid_info的主键和Product的id不一定一致,要通过外键关联查询:bid_info = get_object_or_404(Bid_info, product=product) - 忘记保存Bid_info:你只save了product,但修改的
bid_info.checkclose没保存到数据库,必须加上bid_info.save()
修复后的视图:
def close_bid(request, product_id): product = get_object_or_404(Product, id=product_id) bid_info = get_object_or_404(Bid_info, product=product) if request.method == 'POST': user = request.user # 先判断用户登录,再判断是否为商品卖家 if user.is_authenticated and user == product.user: bid_info.checkclose = True product.active_bool = True bid_info.save() # 一定要保存bid_info的修改! product.save() return redirect('page_product', product_id=product.id) # 非POST请求或权限不足时,返回商品详情页 return redirect('page_product', product_id=product.id)
四、模型设计的小优化建议
目前Bid_info和Product是ForeignKey关联,意味着一个商品可以有多个竞价信息,这显然不符合逻辑(一个商品应该只有一条竞价状态记录)。建议改成OneToOneField,这样查询更方便,也避免数据混乱:
class Bid_info(models.Model): product = models.OneToOneField(Product, on_delete=models.CASCADE, related_name="bid_info") seller = models.ForeignKey(User, on_delete=models.CASCADE, related_name="seller") bid_price = models.DecimalField(max_digits=10, decimal_places=2) checkclose = models.BooleanField(default=False) winner = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
改成OneToOne后,在视图里可以直接用bid_info = product.bid_info获取关联的竞价信息,不用再写get_object_or_404啦~
备注:内容来源于stack exchange,提问作者zahra
相关产品推荐
相关产品推荐

