🔖 Day14 - Post comment, ForeignKey

2018 - 06 - 26
🔖 Day14 - Post comment, ForeignKey
extend User Profile時,利用了models.OneToOneField把每一個User object連接一個Profile。 Django的Field Relation還有:
  • OneToOneField
  • ManyToManyField
  • ForeignKey (即OneToMany)
這次在每一篇post下面加入comment form,要用的是ForeignKey
1. [Create Comment model]models.py加入新model - Comment
from django.db import models
from django.contrib.auth.models import User

class Post(models.Model):
    ...
    ...

class Comment(models.Model):
    parent_post = models.ForeignKey(Post, on_delete=models.CASCADE)
    author = models.ForeignKey(User, one_delete=models.CASCADE)
    content = models.TextField()
    time = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return '%s %s %s' % (self.parent_post, self.author, self.time)

  • 使用ForeignKey把Comment model連接上Post model,即eachPost object is related to many Comment objects
  • 同樣地,eachUser object is related to many Comment objects
  • 使用parent_post, author 以及time作為每篇comment的title string。 e.g.

2. [Create form]forms.py
from django import forms
from .models import Comment

class CommentForm(forms.modelForm):
    content = forms.CharField(required=True, widget=forms.Textarea(attrs={'placeholder':'Comment here...'}))

    class Meta:
        model = Comment
        field = ('content',)


3. [Insert comments in post detail page]views.py把comment session加至每篇post的下面:
from .forms import CommentForm
from .models import Post, Comment
from django.shortcuts import redirect, render
from django.contrib.auth import views as av

def postpage(request, key):
    post = Post.objects.get(pk=key)
    error = ''
    if request.user.is_authenticated:
        if request.method == "POST":
            temp = CommentForm(request.POST)
            if temp.is_valid():
                form = temp.save(commit=False)
                form.parent_post = post
                form.author = request.user
                form.save()
                form = CommentForm()
            else:
                form = CommentForm()
                error = 'There is something wrong of your comment content!'
        else:
            form = CommentForm()
    else:
        form = ''
    return render(request, 'postpage.html', {'post':post, 'comment':comment, 'form':form, 'error':error})

  • 限制只讓已登入用戶留言,利用form = ''在HTML template叫用戶登入
  • 因為Comment model有兩個parameters - parent_post及author不在form顯示,所以要用commit=false的方法自定value,然後再form.save()
  • 因為希望用戶在留comment後可以留在同一頁看到自己的comment,所以在成功form.save()後重新把form assign為unbounded form
  • 用parent_post把該Post object的comments filter成一個list,並放在最後才assign,讓新加的留言可以即時加到comment list裡面。

4. [Modify post detail page template]templates/postpage.html修改內容:
<div>{{ post.content }}</div>
    ...
    ...
    <div>Comments:</div>

    <!--To display comments-->
    {% if comment %}
    {% for c in comment %}
    {{ c.author }}: {{ c.content }}
    {% endfor %}
    {% endif %}

    <!--Check if user is logined-->
    {% if form == '' %}
    <span>Please <a href="{% url 'login' %}?next={{ request.path }}">login</a> to leave comments.</span>
    {% else %}

    <!--Display comment form-->
    <form method="POST">
    {% csrf_token %}
    {{ form.as_p }}
    <input type='submit' Value='Submit'>
    </form>
    {% endif %}

這樣每一篇Post的content下面都會出現
  1. previous comments
  2. new comment form

Comments

There is no comment yet

New Comment

Please Login to comment