django-embed-video/embed_video/fields.py

56 lines
1.6 KiB
Python
Raw Permalink Normal View History

2013-06-01 12:05:25 +00:00
from django.db import models
from django import forms
from django.utils.translation import ugettext_lazy as _
from django import VERSION
2013-06-01 12:05:25 +00:00
from .backends import detect_backend, UnknownIdException, \
2014-02-22 09:22:58 +00:00
UnknownBackendException
2013-06-01 12:05:25 +00:00
__all__ = ('EmbedVideoField', 'EmbedVideoFormField')
class EmbedVideoField(models.URLField):
2013-08-22 08:17:59 +00:00
"""
2016-04-14 09:08:02 +00:00
Model field for embedded video. Descendant of
2013-08-22 08:17:59 +00:00
:py:class:`django.db.models.URLField`.
"""
2013-06-01 12:05:25 +00:00
def formfield(self, **kwargs):
defaults = {'form_class': EmbedVideoFormField}
defaults.update(kwargs)
return super(EmbedVideoField, self).formfield(**defaults)
if VERSION < (1, 9):
def south_field_triple(self):
from south.modelsinspector import introspector
cls_name = '%s.%s' % (
self.__class__.__module__,
self.__class__.__name__
)
args, kwargs = introspector(self)
return (cls_name, args, kwargs)
2013-06-01 13:02:19 +00:00
2013-06-01 12:05:25 +00:00
class EmbedVideoFormField(forms.URLField):
2013-08-22 08:17:59 +00:00
"""
Form field for embeded video. Descendant of
:py:class:`django.forms.URLField`
"""
2013-06-01 12:05:25 +00:00
def validate(self, url):
2014-03-19 21:42:06 +00:00
# if empty url is not allowed throws an exception
2013-06-01 12:05:25 +00:00
super(EmbedVideoFormField, self).validate(url)
2014-07-19 08:08:35 +00:00
2014-03-19 21:42:06 +00:00
if not url:
return
try:
2014-07-19 08:08:35 +00:00
backend = detect_backend(url)
backend.get_code()
2014-03-19 21:42:06 +00:00
except UnknownBackendException:
raise forms.ValidationError(_(u'URL could not be recognized.'))
except UnknownIdException:
raise forms.ValidationError(_(u'ID of this video could not be '
u'recognized.'))
2013-06-01 12:05:25 +00:00
return url