models.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. from pathlib import Path
  2. from django.db import models
  3. from django.core.validators import FileExtensionValidator, MinLengthValidator
  4. from django.contrib.auth.models import AbstractUser
  5. from core.utils.storage import dynamic_upload
  6. class User(AbstractUser):
  7. pass
  8. # This is the best solution to assign multiple unicode ranges
  9. # while keeping admin interface easy to use
  10. # with support of all database engines
  11. class UnicodeRange(models.Model):
  12. start = models.CharField(
  13. max_length=5,
  14. validators=(
  15. MinLengthValidator(4),
  16. )
  17. )
  18. end = models.CharField(max_length=5, default='', blank=True)
  19. name = models.CharField(default='', blank=True, max_length=64)
  20. @property
  21. def range(self) -> str:
  22. return f'{self.start}-{self.end}' if self.end else self.start
  23. def __str__(self) -> str:
  24. return f'{self.name} ({self.range})'
  25. class Meta:
  26. unique_together = ('start', 'end')
  27. class Font(models.Model):
  28. name = models.SlugField(max_length=64, unique=True, db_index=True)
  29. def __str__(self) -> str:
  30. return self.name
  31. class FontFile(models.Model):
  32. OTF = 'otf'
  33. TTF = 'ttf'
  34. WOFF = 'woff'
  35. WOFF2 = 'woff2'
  36. FORMATS = (
  37. (OTF, 'otf'),
  38. (TTF, 'ttf'),
  39. (WOFF, 'woff'),
  40. (WOFF2, 'woff2')
  41. )
  42. file = models.FileField(
  43. upload_to=dynamic_upload('fonts/'),
  44. validators=(
  45. FileExtensionValidator([key for key, _ in FORMATS]),
  46. )
  47. )
  48. name = models.CharField(default='', blank=True, max_length=32)
  49. unicode_ranges = models.ManyToManyField(
  50. UnicodeRange,
  51. related_name='files',
  52. blank=True
  53. )
  54. font = models.ForeignKey(
  55. Font,
  56. on_delete=models.CASCADE,
  57. related_name='files'
  58. )
  59. @property
  60. def suffix(self):
  61. path = Path(self.file.path)
  62. return path.suffix
  63. @property
  64. def format(self):
  65. return self.suffix[1:]
  66. def __str__(self) -> str:
  67. return self.name or self.font.name