I'm creating an app like reddit where you can post videos and texts.
I want to let the user choose between video and image field but not both
here is what I've done:
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')
this shows the validationError
but even when the user only fills the video fileField
and not the texField
it still shows the validationError
UPDATE
I've changed if text is not None and video is not None:
to
if text != '' and video is not None:
and now it works.
I still don't know why not None
didn't work for text.
CodePudding user response:
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 ----'
CodePudding user response:
Use required=False
instead of blank = True
class CreatePostForm(ModelForm):
video = forms.FileField(required=False)
image = forms.FileField(required=False)
...