-
Notifications
You must be signed in to change notification settings - Fork 135
/
Copy pathfields.py
51 lines (41 loc) · 1.39 KB
/
fields.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
from django import forms
from django.db import models
from django.utils.translation import gettext_lazy as _
from embed_video.backends import (
UnknownBackendException,
UnknownIdException,
VideoDoesntExistException,
detect_backend,
)
__all__ = ("EmbedVideoField", "EmbedVideoFormField")
class EmbedVideoField(models.URLField):
"""
Model field for embedded video. Descendant of
:py:class:`django.db.models.URLField`.
"""
def formfield(self, **kwargs):
defaults = {"form_class": EmbedVideoFormField}
defaults.update(kwargs)
return super().formfield(**defaults)
class EmbedVideoFormField(forms.URLField):
"""
Form field for embeded video. Descendant of
:py:class:`django.forms.URLField`
"""
def validate(self, url):
# if empty url is not allowed throws an exception
super().validate(url)
if not url:
return
try:
backend = detect_backend(url)
backend.get_code()
except UnknownBackendException:
raise forms.ValidationError(_("URL could not be recognized."))
except UnknownIdException:
raise forms.ValidationError(
_("ID of this video could not be " "recognized.")
)
except VideoDoesntExistException:
raise forms.ValidationError(_("This media not found on site."))
return url