Django开发拍卖网站提交商品表单创建Listing实例触发TypeError
报错原因
你触发TypeError的直接原因是Listing模型不存在名为user的字段,你在定义外键时错误使用了name参数覆盖了字段名,同时还有多处模型定义和视图逻辑的错误,按以下步骤修改即可:
第一步:修正models.py的错误
你之前对模型字段的name参数、外键默认值、魔法方法的使用都有问题,修正后的代码如下:
class Listing(models.Model): title = models.CharField(max_length=200) description = models.CharField(max_length=500) url = models.URLField() # 删除错误的name参数,避免覆盖字段名,直接保留user作为字段名 user = models.ForeignKey('User', on_delete=models.CASCADE) # 外键默认值不能是空字符串,允许无分类就加null=True、blank=True category = models.ForeignKey('Category', on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return f'{self.id}: {self.title}' class Bid(models.Model): price = models.DecimalField(decimal_places=2, max_digits=10) bid_count = models.IntegerField() # 修正外键默认值配置 listing = models.ForeignKey('Listing', on_delete=models.CASCADE, null=True, blank=True) def __str__(self): # 删除不存在的slug字段引用 return f'{self.id} ({self.price})'
如果你想把用户字段命名为author,就把Listing的用户字段改为author = models.ForeignKey('User', on_delete=models.CASCADE),后面创建实例时参数对应传author=request.user即可。
第二步:修正views.py的错误
def newListing(request): try: if request.method == "POST": newListingForm = NewListingForm(request.POST) if newListingForm.is_valid(): title = newListingForm.cleaned_data['title'] description = newListingForm.cleaned_data['description'] url = newListingForm.cleaned_data['url'] bid = newListingForm.cleaned_data['bid'] category = newListingForm.cleaned_data['category'] current_user = request.user # 字段名和模型保持一致,直接传用户实例即可,不需要单独传id l = Listing(title=title, description=description, url=url, user=current_user, category=category) l.save() b = Bid(price=bid, bid_count=0) # ForeignKey是单值字段直接赋值即可,add是多对多字段的方法,不能用在外键上 b.listing = l b.save() return HttpResponseRedirect(reverse("index")) else: newListingForm = NewListingForm() return render(request, "auctions/newListing.html", { 'form': newListingForm }) except Exception as exc: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] # 加上打印异常详情,后续排查问题更方便 print(exc_type, fname, exc_tb.tb_lineno, str(exc_obj)) newListingForm = NewListingForm() return render(request, 'auctions/newListing.html', { 'form': newListingForm })
修改完成后执行python manage.py makemigrations和python manage.py migrate同步数据库结构即可正常运行。
内容的提问来源于stack exchange,提问作者amiller_lite
相关产品推荐
相关产品推荐

