Coverage for snippets/models.py: 100.00%

29 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-10-19 21:53 -0700

1from django.contrib.auth import get_user_model 1a

2from django.db import models 1a

3from pygments import highlight 1a

4from pygments.formatters.html import HtmlFormatter 1a

5from pygments.lexers import get_all_lexers, get_lexer_by_name 1a

6from pygments.styles import get_all_styles 1a

7 

8LEXERS = [item for item in get_all_lexers() if item[1]] 1a

9LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS]) 1a

10STYLE_CHOICES = sorted((item, item) for item in get_all_styles()) 1a

11 

12 

13class Snippet(models.Model): 1a

14 created = models.DateTimeField(auto_now_add=True) 1a

15 title = models.CharField(max_length=100, blank=True, default="") 1a

16 code = models.TextField() 1a

17 linenos = models.BooleanField(default=False) 1a

18 language = models.CharField( 1a

19 choices=LANGUAGE_CHOICES, default="python", max_length=100 

20 ) 

21 style = models.CharField(choices=STYLE_CHOICES, default="friendly", max_length=100) 1a

22 owner = models.ForeignKey( 1a

23 get_user_model(), related_name="snippets", on_delete=models.CASCADE 

24 ) 

25 highlighted = models.TextField() 1a

26 

27 class Meta: 1a

28 ordering = ("created",) 1a

29 

30 def __str__(self): 1a

31 return self.title 1a

32 

33 def save(self, *args, **kwargs): 1a

34 """ 

35 Use the 'pygments' library to create a highlighted HTML 

36 representation of the code snippet. 

37 """ 

38 lexer = get_lexer_by_name(self.language) 1a

39 linenos = "table" if self.linenos else False 1a

40 options = {"title": self.title} if self.title else {} 1a

41 formatter = HtmlFormatter( 1a

42 style=self.style, linenos=linenos, full=True, **options 

43 ) 

44 self.highlighted = highlight(self.code, lexer, formatter) 1a

45 super().save(*args, **kwargs) 1a