我有一个可以访问 Api 并返回 json 数据的模型
class Video(models.Model):
url = models.URLField(_('URL'), blank=True)
type = models.CharField(max_length=10, null=True, blank=True)
def get_oembed_info(self, url):
api_url = 'http://api.embed.ly/1/oembed?'
params = {'url': url, 'format': 'json'}
fetch_url = 'http://api.embed.ly/1/oembed?%s' % urllib.urlencode(params)
result = urllib.urlopen(fetch_url).read()
result = json.loads(result)
return result
def get_video_info(self):
url = self.url
result = self.get_oembed_info(url)
KEYS = ('type', 'title', 'description', 'author_name')
for key in KEYS:
if result.has_key(key):
setattr(self, key, result[key])
def save(self, *args, **kwargs):
if not self.pk:
self.get_video_info()
super(Video, self).save(*args, **kwargs)
class VideoForm(forms.ModelForm):
def clean(self):
if not self.cleaned_data['url'] and not self.cleaned_data['slide_url']:
raise forms.ValidationError('Please provide either a video url or a slide url')
return self.cleaned_data
我想在提交表单时访问类型字段,因此如果类型不是“某物”,则会引发错误,如上述 clean 方法。或者如何在 VideoForm 类中访问 get_oembed_info 方法结果。
解决方案
正如 Thomas 所说,调用模型的 clean 方法然后施展魔法
def clean(self):
self.get_video_info()
if self.type == 'something':
raise ValidationError("Message")