Adding information to our model

We're going to make a couple of changes to our Snippet model class.First, let's add a couple of fields. One of those fields will be used to represent the user who created the code snippet. The other field will be used to store the highlighted HTML representation of the code.

Add the following two fields to the Snippet model in models.py.

  1. owner = models.ForeignKey('auth.User', related_name='snippets', on_delete=models.CASCADE)
  2. highlighted = models.TextField()

We'd also need to make sure that when the model is saved, that we populate the highlighted field, using the pygments code highlighting library.

We'll need some extra imports:

  1. from pygments.lexers import get_lexer_by_name
  2. from pygments.formatters.html import HtmlFormatter
  3. from pygments import highlight

And now we can add a .save() method to our model class:

  1. def save(self, *args, **kwargs):
  2. """
  3. Use the `pygments` library to create a highlighted HTML
  4. representation of the code snippet.
  5. """
  6. lexer = get_lexer_by_name(self.language)
  7. linenos = 'table' if self.linenos else False
  8. options = {'title': self.title} if self.title else {}
  9. formatter = HtmlFormatter(style=self.style, linenos=linenos,
  10. full=True, **options)
  11. self.highlighted = highlight(self.code, lexer, formatter)
  12. super(Snippet, self).save(*args, **kwargs)

When that's all done we'll need to update our database tables.Normally we'd create a database migration in order to do that, but for the purposes of this tutorial, let's just delete the database and start again.

  1. rm -f db.sqlite3
  2. rm -r snippets/migrations
  3. python manage.py makemigrations snippets
  4. python manage.py migrate

You might also want to create a few different users, to use for testing the API. The quickest way to do this will be with the createsuperuser command.

  1. python manage.py createsuperuser