You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django表单问题:提交重定向失败与模型对象不可迭代

Django反馈表单问题排查与修复

1. 'BugTypes' object is not iterable 错误修复

这个错误由两个问题导致:

  • 多对多字段与表单控件不匹配:模型UserFeedback中bugType是ManyToManyField(支持关联多个Bug类型),但表单里用了ModelChoiceField(单选控件),提交时返回单个BugTypes对象,而多对多字段需要接收可迭代的对象列表,因此触发“不可迭代”错误。
  • 模型方法拼写错误:UserFeedback的__str__方法中self. Problem是笔误,应为self.problem(小写p),会导致对象序列化异常。

修正代码:

models.py:

class UserFeedback(models.Model):
    username = models.CharField(max_length=100)
    problem = models.CharField(max_length=255)
    bugType = models.ManyToManyField("BugTypes", related_name='userFeedBack')
    feedback = models.TextField()
    
    def __str__(self):
        return self.problem  # 修正大写P为小写p

forms.py(二选一):

  • 若业务需要支持多选Bug类型,替换为多选控件:
bugType = forms.ModelMultipleChoiceField(
    queryset = BugTypes.objects.all(), 
    widget = forms.SelectMultiple(attrs={'class': 'form-control'})
)
  • 若业务仅支持单选Bug类型,修改模型字段为外键:
# models.py中修改bugType字段
bugType = models.ForeignKey("BugTypes", related_name='userFeedBack', on_delete=models.CASCADE)
# 表单可保留原ModelChoiceField

2. 提交后无法返回空白表单的修复

当前硬编码的success_url与路由规则不匹配,且未遵循Django动态URL生成规范,导致重定向异常。

修正views.py:

from django.urls import reverse_lazy

class UserFeedbackView(CreateView):
    model = UserFeedback
    form_class = FeedbackForm
    success_url = reverse_lazy('survey:userFeedback')  # 动态生成目标URL

可选:修正urls.py路由(符合Django斜杠规范):

urlpatterns = [
    path('feedback/', view = userFeedback_view, name='userFeedback')  # 添加结尾斜杠
]

提交成功后会自动重定向到空白反馈表单页面。

内容的提问来源于stack exchange,提问作者ShanN

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 21:50:15