【问题标题】:CreateView is throwing "DoesNotExist" when instance isn't provided to form当实例未提供给表单时,CreateView 抛出“DoesNotExist”
【发布时间】:2012-02-02 01:52:16
【问题描述】:

我在以下设置中收到“DoesNotExist”错误 - 我尝试调试了一段时间,但无法弄清楚。

class Video(models.Model):
    name = models.CharField(max_length=100)
    type = models.CharField(max_length=100)
    owner =  models.ForeignKey(User, related_name='videos')
    ...
    #Related m2m fields
    ....

class VideoForm(modelForm):
    class Meta:
        model = Video
        fields = ('name', 'type')

class VideoCreate(CreateView):
    template_name = 'video_form.html'
    form_class = VideoForm
    model = Video

当我这样做并发布“名称”和“类型”的数据时 - 我收到“DoesNotExist”错误。它似乎与 UpdateView 一起工作正常 - 或者当传递一个“实例”来初始化表单时。

这是引发错误的确切位置: /usr/lib/pymodules/python2.7/django/db/models/fields/related.py 在 get,第 301 行

有人知道会发生什么吗?

谢谢

【问题讨论】:

    标签: django django-models django-forms django-class-based-views


    【解决方案1】:

    由于您尚未发布完整的回溯,我猜您的所有者 FK 不是可选的,并且您没有在模型表单中指定一个。

    您需要发布完整的回溯。

    【讨论】:

    • 啊,你是对的 - 我在我的表单验证方法中使用了所有者,但没有在我的表单定义中指定它。谢谢!
    【解决方案2】:

    我认为它必须是 VideoForm(ModelForm) 而不是 VideoForm(modelForm)

    如果您不打算在表单中使用外键,请使用 exclude = ('owner')

    【讨论】:

      猜你喜欢
      • 2013-11-03
      • 2016-03-28
      • 2020-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多