【问题标题】:Getting an error while using Django Model Form in views.py在 views.py 中使用 Django 模型表单时出错
【发布时间】:2012-06-30 22:49:18
【问题描述】:

在我的models.py中

 class Alert(models.Model):

    user = models.CharField(max_length=30, blank=True)
    a = models.IntegerField(blank=True)
    def __unicode__(self):
        return "'%s' at %s" % (self.user)

在我的 forms.py 中:

 class AlertForm(forms.ModelForm):
    class Meta:
        model=Alert
        fields = ('a','user')
        widgets = {
            'user': forms.HiddenInput()
        }

AlertCountFormset = modelformset_factory(Alert,
                                        form = AlertForm)

在我看来.py:

def profile_setting(request, slug):
if request.method == 'GET':
    form = AlertForm(request.POST)
    if form.is_valid():
        alert_form = form.save(commit=False)
        alert_form.user = request.user.username
        alert_form.save() # Here i am getting the error
        return HttpResponseRedirect('/user/list')

extra_context = {
    'form': AlertForm()
}
return direct_to_template(request,'users/profile_setting.html',
                          extra_context)

我正在尝试填写 Django 模型表单,但我正在关注 error 我曾在其中发表评论:

events_alertcount.a may not be NULL

这是什么?即使将null=True 放在a 的字段中,它也会显示相同的错误。我的forms.py or models.py 有问题吗?

【问题讨论】:

  • 您的视图代码的 sn-p 也有错误,这并不重要。但是您再次检查请求 GET 并从 POST 收集表单。

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


【解决方案1】:

这也是在数据库级别强制执行的。在您的数据库中设置您的“a”列以允许该字段为 NULL。这应该解决它。 HTH。

【讨论】:

  • 我没有得到你。您是要我这样做 a = models.IntegerField(blank=True, null=True) 吗?
  • 是的,您必须在“a”上声明。如果您在没有 null=True 的情况下运行 syncdb,您的数据库将将该字段设置为不接受 NULL 作为值。因此,您必须更改 db 列以接受 NULL 作为值。您也可以在将 a 更改为 a = models.IntegerField(blank=True, null=True) 后删除 db 表并再次运行 syncdb。但请在删除表格之前进行备份,因为表格已经填满了您的数据。
【解决方案2】:

试试这个:

a = models.IntegerField(blank=True, null=True)

你应该再次调用syncdb

【讨论】:

  • syncdb 不会更改现有的数据库表!
【解决方案3】:

在定义模型字段时,blank 选项与验证相关,这意味着如果您将blank 设置为 true,则如果未填写该字段,验证将不会失败。

blank 与验证相关。如果一个字段有blank=True,Django 管理站点上的验证将允许输入一个空值。如果某个字段有blank=False,则该字段为必填项。

但是,如果验证没有失败并且您保存了模型,则该字段将持久保存到数据库中。现在,除非您将 null 选项设置为 true,否则数据库中的字段不能为 null

null 纯粹与数据库相关,而空白与验证相关。

话虽如此,您可以通过将 null 选项添加到 Alert.a 来修复错误:

a = models.IntegerField(blank=True, null=True)

现在,如果您已经运行了 syncdb 命令,则需要删除您的表,然后重新运行 syncdb 以获取此更改。如果此数据库是生产数据库并且您无法执行此操作,请查看django-south,了解如何迁移架构和数据。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-06
    • 2014-03-30
    • 2018-07-14
    • 1970-01-01
    • 1970-01-01
    • 2014-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多