2017-09-06 63 views
0

我有以下形式:排除領域仍然需要

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字段錯誤:該字段是必需的。

我想在form.is_valid方法之後填充這個字段。

由於此字段不在所需的字段元組中,是否不需要它?

我也嘗試添加:

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

雖然我得到同樣的錯誤。

還有別的事情嗎?

+0

如果您希望post_type爲null,然後添加null = True,那麼在模型中所需的表單和字段之間存在不同的字段,否則您可以在調用is_valid之前填充它,這不會影響附加內容因爲你不關心這個領域顯然是對的? – Quentin

回答

1
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)在models.py不行,因爲你的ModelForm有覆蓋post_type領域,如果你想不將其設置爲required=False


post_type = models.IntegerField(choices=POST_CHOICES, blank=True)工作時間:

class PostForm(forms.ModelForm): 

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