This repository has been archived on 2022-09-23. You can view files and clone it, but cannot push or open issues or pull requests.
webdev/website/snippets/models.py

39 lines
1.6 KiB
Python
Raw Normal View History

2022-01-08 00:12:34 +01:00
from django.db import models
2022-01-08 00:40:31 +01:00
# pygments
from pygments import highlight
2022-01-08 00:12:34 +01:00
from pygments.lexers import get_all_lexers
from pygments.styles import get_all_styles
2022-01-08 00:40:31 +01:00
from pygments.lexers import get_lexer_by_name
from pygments.formatters.html import HtmlFormatter
2022-01-08 00:12:34 +01:00
LEXERS = [item for item in get_all_lexers() if item[1]]
LANGUAGE_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 = models.DateTimeField(auto_now_add=True)
# modified?
title = models.CharField(max_length=100, blank=True, default='')
code = models.TextField()
linenos = models.BooleanField(default=False)
language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100)
style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100)
2022-01-08 00:40:31 +01:00
owner = models.ForeignKey('auth.user', related_name='snippets', on_delete=models.CASCADE)
highlighted = models.TextField
2022-01-08 00:12:34 +01:00
class Meta:
2022-01-08 00:40:31 +01:00
ordering = ['created']
def save(self, *args, **kwargs):
"""
Use the `pygments` library to create a highlighted HTML
representation of the code snippet.
"""
lexer = get_lexer_by_name(self.language)
linenos = 'table' if self.linenos else False
options = {'title': self.title} if self.title else {}
formatter = HtmlFormatter(style=self.style, linenos=linenos,
full=True, **options)
self.highlighted = highlight(self.code, lexer, formatter)
super().save(*args, **kwargs)