Create your models: Posts

  1. Create your models
  2. Authors

The basic unit of our blog is the post. Each post has a title, some content, the date it was published, whether or not it is public, some topics, an author, and when it was last edited.

Open models.py and create your Post model.

class Post(models.Model):

title = models.CharField(max_length=120)

slug = models.SlugField(unique=True)

content = models.TextField()

date = models.DateTimeField()

live = models.BooleanField(default=False)

topics = models.ManyToManyField(Topic, blank=True)

author = models.ForeignKey(Author)

changed = models.DateTimeField(auto_now=True)

def __unicode__(self):

return self.title

I like to include a “changed” or “modified” timestamp on every model. It makes a lot of things easier down the line, and it also helps you see recent changes in the admin.

The “slug” is what we’ll use for the URL of the post. Titles often have URL-unfriendly characters such as spaces, ampersands, percentages, and other strange things. The slug must be unique, because if two posts had the same slug, there would be no way to differentiate their URLs.

The Post class is a subclass of Django’s built-in Model class. We’ll see later that this means it inherits a lot of useful functionality.

The “__unicode__” method tells Django, and Python, how to display each instance of the class when displaying it as a string of text.

  1. Create your models
  2. Authors