35 lines
1.4 KiB
Python
35 lines
1.4 KiB
Python
from django.db import models
|
|
|
|
from pygments.lexers import get_all_lexers, get_lexer_by_name
|
|
from pygments.styles import get_all_styles
|
|
from pygments.formatters.html import HtmlFormatter
|
|
from pygments import highlight
|
|
|
|
|
|
|
|
LEXERS = [item for item in get_all_lexers() if item[1]]
|
|
LANG_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS])
|
|
STYLE_CHOICES = sorted([(item, item) for item in get_all_styles()])
|
|
|
|
class Snippet(models.Model):
|
|
created_at = models.DateTimeField(auto_now=True)
|
|
title = models.CharField(max_length=100, blank=True, default="")
|
|
code = models.TextField()
|
|
line_numbers = models.BooleanField(default=False)
|
|
language = models.CharField(choices=LANG_CHOICES, default="python", max_length=100)
|
|
style = models.CharField(choices=STYLE_CHOICES, default="friendly", max_length=100)
|
|
owner = models.ForeignKey("auth.User", related_name="snippets", on_delete=models.CASCADE)
|
|
highlighted = models.TextField()
|
|
|
|
class Meta:
|
|
ordering = ["created_at"]
|
|
|
|
def save(self, *args, **kwargs):
|
|
lexer = get_lexer_by_name(self.language)
|
|
line_nums = "table" if self.line_numbers else False
|
|
options = {"title": self.title} if self.title else {}
|
|
formatter = HtmlFormatter(style=self.style, linenos=line_nums, full=True, **options)
|
|
self.highlighted = highlight(self.code, lexer, formatter)
|
|
super().save(*args, **kwargs)
|
|
|