允许用户只填写一个字段而不是两个 |姜戈

Allow user to fill only one of the fields not both | Django

我正在创建一个类似 reddit 的应用程序,您可以在其中 post 视频和文本。

我想让用户在视频和图像字段之间进行选择,但不能同时选择两者

这是我所做的:

class CreatePostForm(ModelForm):
    class Meta:
        model = Post
        fields = ['title','video','image','text']
        widgets ={'title':forms.TextInput({'placeholder':'تیتر'}), 'text':forms.Textarea({'placeholder':'متن'})}    
    
    def clean(self):
        cleaned_data = super().clean()
        text = cleaned_data.get("text")
        video = cleaned_data.get("video")
        if text is not None and video is not None:
            raise ValidationError('this action is not allowed', 'invalid')

这会显示 validationError ,但是 即使用户只填充视频 fileField 而不是 texField 它仍然显示 validationError

更新

我变了if text is not None and video is not None:if text != '' and video is not None: 现在它起作用了。 我仍然不知道为什么 not None 对文本不起作用。

使用required=False代替blank = True

class CreatePostForm(ModelForm):
    video = forms.FileField(required=False)
    image = forms.FileField(required=False)
    ...
def make_decision(text = None,video=None):
    if text != '' and video != '':
        print('--------- Both are not possible for selection ---------')
    elif text != '':
        text = '--------- calling only text ---------'
        print(text)
    elif video != '':
        video = '--------- calling only video ---------'
        print(video)
    else:
        print('--------- Please select atleast one ---------')

# ------ Possibility for calling function (test cases) --------------
make_decision('','')   # raise_error = '--------- Both are not possible for selection ---------'
# make_decision('y','')  # '--------- calling only text ---------'
# make_decision('','y')  # '--------- calling only video ---------'
# make_decision('','') # '--------- Please select atleast one ----'