Django模型空白= True,但sql始终不为NULL

时间:2017-09-21 13:44:43

标签: python django django-models django-forms

我正在从教程构建一个Django网站。该模型名为Post,看起来像这样:

class Post(models.Model):
   author = models.ForeignKey('auth.User', verbose_name='Author')
   title = models.CharField(max_length=200, verbose_name='Titel')
   text = HTMLField()
   created_date = models.DateTimeField(default=timezone.now, verbose_name='Erstellungsdatum')
   published = models.BooleanField(blank=True, verbose_name='Veröffentlichung')
   tags = models.ManyToManyField(Tag, blank=True)

   class Meta:
       verbose_name = 'Artikel'
       verbose_name_plural = 'Artikels'
       ordering = ['-created_date']

   def publish(self):
       self.published = True
       self.save()

   def __str__(self):
       return self.title

如您所见,我制作了一些字段blank=True

migration / sql Django现在的表现如下:

ALTER TABLE "blog_post" RENAME TO "blog_post__old";
CREATE TABLE "blog_post" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, 
"published" bool NOT NULL, "title" varchar(200) NOT NULL, "text" text NOT 
NULL, "created_date" datetime NOT NULL, "author_id" integer NOT NULL 
REFERENCES "auth_user" ("id"));
INSERT INTO "blog_post" ("id", "title", "text", "created_date", "author_id", 
"published") SELECT "id", "title", "text", "created_date", "author_id", 
"published" FROM "blog_post__old";
DROP TABLE "blog_post__old";
CREATE INDEX "blog_post_author_id_dd7a8485" ON "blog_post" ("author_id");
COMMIT;

它只是忽略空值并使每个字段都为NOT NULL。 我也在question

中看到了这一点

问题是,如果我在模板中实现表单,则此字段是“必需”输入,因此如果取消选中该复选框,则无法提交表单。

提前致谢!

forms.py

from django import forms
from tinymce.widgets import TinyMCE

from .models import Post

class PostForm(forms.ModelForm):

    text = forms.CharField(widget=TinyMCE(attrs={'cols': 80, 'rows': 30, 'class': 'materialize-textarea'}))
    published = forms.BooleanField(widget=forms.CheckboxInput())

    class Meta:
        model = Post
        fields = ('title', 'published', 'text', 'tags')

模板

{% extends 'blog/base.html' %}

{% block content_block %}
    <div class="row">
        <h1>Edit Post</h1>
    </div>

<div class="row">
    <form class="col s12" action="" method="POST">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit" class="waves-effect waves-light btn"><i class="material-icons left">save</i>Speichern</button>
    </form>
</div>

{% endblock %}

2 个答案:

答案 0 :(得分:0)

published = models.BooleanField(blank=True, verbose_name='Veröffentlichung')

来源参考文档django model references

  

请注意,这与null不同。 null纯粹   与数据库相关,而空白与验证相关。如果有一个字段   blank = True,表单验证将允许输入空值。如果一个   field为blank = False,将需要该字段。

在表格中

published = forms.BooleanField(required=False,widget=forms.CheckboxInput())

来源Requred filed

希望它的工作

答案 1 :(得分:0)

BooleanField可以存储TrueFalse,因此NOT NULL不是问题。

如果您确实要允许某个字段null,则需要null=True。这是您已经拥有的blank=True的单独选项。

您不应该覆盖模型表单中的布尔字段,因为它已经是一个复选框。但是,如果您覆盖它,那么如果您希望该字段是可选字段,则需要设置required=False

published = forms.BooleanField(widget=forms.CheckboxInput(), required=False)