Skip to content
juyaolongpaul edited this page Apr 15, 2018 · 1 revision

In this page, we will introduce how post and comment are defined so views.py can create different views for them, which will create a tag for the template HTML to refer.

First, models.py is the place where the models are defined. Posts are defined as:

class Post(models.Model):  # what do you want a post to be? Define it here
    author = models.ForeignKey('auth.User', on_delete=models.DO_NOTHING)  # author connects the superuser on the website
    # , which will pop out a menu for you to choose which superuser
    title = models.CharField(max_length=200)
    text = models.TextField()
    created_date = models.DateTimeField(default=timezone.now)
    published_date = models.DateTimeField(blank=True, null=True)

    def publish(self):
        self.published_date = timezone.now()
        self.save()  # if you change the attribute of the class, you need to save it

    def approve_comments(self):
        return self.comments.filter(approved_comment=True)

    def get_absolute_url(self):
        return reverse("post_detail", kwargs={'pk': self.pk})  # After creating a post, go to 'post_detail' page,
        # with the primary key you just created

    def __str__(self):
        return self.title

Each post needs an author, so each post is linked with a user by using ForeignKey, which describes the many-to-one relationship: One author might have multiple posts. See here for the detailed documentation. The author is defined as auth.User, which you can create through Django shell or develop a function that it can be created using front-end web page (we will discuss this later).

Also, the post has several variables: title, text, created_date, published_date. Additionally, a post has publish, approve_comments, get_absolute_url functions. Many functions will be called in views.py, which we will explain in details later.

Similarly, comment is defined as follow:

class Comment(models.Model):  # this model is related to post model, some connections are needed
    post = models.ForeignKey('blog.Post', related_name='comments', on_delete=models.DO_NOTHING)
    author = models.CharField(max_length=200)  # If user is defined this way, you can just put a name into the text area
    text = models.TextField()
    created_date = models.DateTimeField(default=timezone.now)
    approved_comment = models.BooleanField(default=False)

    def approve(self):
        self. approved_comment = True  # if the comment is approved, save it
        self.save()

    def get_absolute_url(self):
        return reverse('post_list')  # When you commented, go back to the post list

    def __str__(self):
        return self.text

As we can see Comment forms the many-to-one relationship with Post: Each post can have many comments.

Clone this wiki locally