代码之家  ›  专栏  ›  技术社区  ›  Atma

模型表单中的排除字段仍为必填字段

  •  0
  • Atma  · 技术社区  · 8 年前

    class PostForm(forms.ModelForm):
        post_type = forms.ChoiceField(widget=forms.RadioSelect(attrs={'name': 'radioInline'}), choices=POST_CHOICES)
    
    
        class Meta:
            model = Post
            fields = ('title','desc','image','url',) 
    

    我有以下型号:

    @python_2_unicode_compatible
    class Post(models.Model):  
        entity = models.ForeignKey('companies.Entity')
        title = models.CharField('Post Title', max_length=128, unique=True) 
        desc = models.TextField('Description', blank=True, null=True)
        post_type = models.IntegerField(choices=POST_CHOICES)
        image = models.ImageField('Post Image', upload_to='post', blank=True, null=True)
        url = models.URLField(max_length=255, blank=True, null=True)
        slug = models.SlugField(blank=True, null=True, unique=True)
        created_at = models.DateTimeField(auto_now_add = True)
        updated_at = models.DateTimeField(auto_now = True)
    

    当我提交表单时,我得到了错误:

    我想在表单后填充此字段。是有效方法。

    既然这个字段不在必填字段元组中,那么它不应该是必填字段吗?

    我还尝试添加:

    post_type = models.IntegerField(choices=POST_CHOICES, blank=True)
    

    虽然我也犯了同样的错误。

    1 回复  |  直到 8 年前
        1
  •  1
  •   Ykh    8 年前
    post_type = forms.ChoiceField(widget=forms.RadioSelect(attrs={'name': 'radioInline'}), choices=POST_CHOICES, required=False)
    

    添加 required=False


    你的 post_type = models.IntegerField(choices=POST_CHOICES, blank=True) 必需=False


    post_类型=模型。IntegerField(选项=POST\u选项,空白=True) 只工作:

    class PostForm(forms.ModelForm):
    
        class Meta:
            model = Post
            fields = ('title','desc','image','url', 'post_type')