forms.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. __package__ = 'archivebox.core'
  2. from django import forms
  3. from ..util import URL_REGEX
  4. from ..vendor.taggit_utils import edit_string_for_tags, parse_tags
  5. CHOICES = (
  6. ('0', 'depth = 0 (archive just these URLs)'),
  7. ('1', 'depth = 1 (archive these URLs and all URLs one hop away)'),
  8. )
  9. from ..extractors import get_default_archive_methods
  10. ARCHIVE_METHODS = [
  11. (name, name)
  12. for name, _, _ in get_default_archive_methods()
  13. ]
  14. class AddLinkForm(forms.Form):
  15. url = forms.RegexField(label="URLs (one per line)", regex=URL_REGEX, min_length='6', strip=True, widget=forms.Textarea, required=True)
  16. depth = forms.ChoiceField(label="Archive depth", choices=CHOICES, widget=forms.RadioSelect, initial='0')
  17. archive_methods = forms.MultipleChoiceField(
  18. required=False,
  19. widget=forms.SelectMultiple,
  20. choices=ARCHIVE_METHODS,
  21. )
  22. class TagWidgetMixin:
  23. def format_value(self, value):
  24. if value is not None and not isinstance(value, str):
  25. value = edit_string_for_tags(value)
  26. return super().format_value(value)
  27. class TagWidget(TagWidgetMixin, forms.TextInput):
  28. pass
  29. class TagField(forms.CharField):
  30. widget = TagWidget
  31. def clean(self, value):
  32. value = super().clean(value)
  33. try:
  34. return parse_tags(value)
  35. except ValueError:
  36. raise forms.ValidationError(
  37. "Please provide a comma-separated list of tags."
  38. )
  39. def has_changed(self, initial_value, data_value):
  40. # Always return False if the field is disabled since self.bound_data
  41. # always uses the initial value in this case.
  42. if self.disabled:
  43. return False
  44. try:
  45. data_value = self.clean(data_value)
  46. except forms.ValidationError:
  47. pass
  48. if initial_value is None:
  49. initial_value = []
  50. initial_value = [tag.name for tag in initial_value]
  51. initial_value.sort()
  52. return initial_value != data_value