Creating a model to work with

For the purposes of this tutorial we're going to start by creating a simple Snippet model that is used to store code snippets. Go ahead and edit the snippets/models.py file. Note: Good programming practices include comments. Although you will find them in our repository version of this tutorial code, we have omitted them here to focus on the code itself.

  1. from django.db import models
  2. from pygments.lexers import get_all_lexers
  3. from pygments.styles import get_all_styles
  4. LEXERS = [item for item in get_all_lexers() if item[1]]
  5. LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS])
  6. STYLE_CHOICES = sorted([(item, item) for item in get_all_styles()])
  7. class Snippet(models.Model):
  8. created = models.DateTimeField(auto_now_add=True)
  9. title = models.CharField(max_length=100, blank=True, default='')
  10. code = models.TextField()
  11. linenos = models.BooleanField(default=False)
  12. language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100)
  13. style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100)
  14. class Meta:
  15. ordering = ['created']

We'll also need to create an initial migration for our snippet model, and sync the database for the first time.

  1. python manage.py makemigrations snippets
  2. python manage.py migrate