开发者

Django Models, ModelForm and validation

开发者 https://www.devze.com 2023-02-16 11:15 出处:网络
For the following model: #models.py class en开发者_Go百科try(models.Model): title = models.CharField(max_length=25)

For the following model:

#models.py
class en开发者_Go百科try(models.Model):
    title = models.CharField(max_length=25)
    image = models.ImageField(upload_to="/",blank=True)
    video_url = models.CharField(max_length=150,blank=True)

I want the model and corresponding ModelForm only be allowed either an image field or a video_url field, but not both.

How is this best accomplished? Do I need to validate on the model, the modelform, or both?


in your form you can use:

def clean(self):
    cleaned_data = self.cleaned_data
    m_image = cleaned_data.get('imagee')
    m_video_url = cleaned_data.get('video_url')

    if (m_image and m_video_url): 
        raise forms.ValidationError("Both video url and image sumbitted")

    return cleaned_data
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号