Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
567 views
in Technique[技术] by (71.8m points)

forms - Django, how to display comments on a blog post in post template only for login user

Django, how to display comments on a blog post in post template only for login user , i made these below mentioned models & views. Now my comments are successfully storing in database with name of user but the problem is its not shown on post . so far only count is displaying to see how many comments posted so far!

def get_comments(self):
    return self.comments.all().order_by('-timestamp')

class Comment(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    timestamp = models.DateTimeField(auto_now_add=True)
    commentfield = models.TextField()
    post = models.ForeignKey(Blogpost, related_name='comments', on_delete=models.CASCADE)

    def __str__(self):
        return self.user.username

**My Forms**

from django import forms
from .models import Blogpost, Comment


class CommentForm(forms.ModelForm):
    commentfield  = forms.CharField(widget=forms.Textarea(attrs={
        'class': 'form-control',
        'placeholder': 'Type your comment',
        'id': 'usercomment',
        'rows': '4'
    }))
    class Meta:
        model = Comment
        fields = ("commentfield",)

**My Blog Post Views**

def blogpost(request, year, month, day, post):
    category_count= get_category_count()
    latest = Blogpost.objects.order_by('-publish')[0:4]
    post = get_object_or_404(Blogpost, slug= post)
    form = CommentForm(request.POST or None)
    if request.method == "POST":
        if form.is_valid():
            form.instance.user = request.user
            form.instance.post = post
            form.save()
            return redirect('.')
    context = {'post':post,
    'latest': latest,
    'category_count': category_count,
    'form': form,
    }
    return render(request, 'blog/blogpost.html', context)

**My Templates** 
<div class="post-comments">
                            <header>
                                <h3 class="h6">Post Comments<span class="no-of-comments">
                                    ({{ post.comments.count }})</span></h3>
                            </header>
                            {% for comment in post.get_comments %}
                            <div class="comment">
                                <div class="comment-header d-flex justify-content-between">
                                    <div class="user d-flex align-items-center">
                                        <div class="image">
                                            {% if comment.user.author %}
                                            <img src="{{ comment.user.author.profile_picture.url }}" alt="..."
                                                class="img-fluid rounded-circle">
                                            {% else %}
                                            <img src="" alt="..."
                                                class="img-fluid rounded-circle">
                                            {% endif %}
                                        </div>
                                        <div class="title"><strong>{{ comment.user.username }}</strong><span
                                                class="date">{{ comment.timestamp|timesince }} ago</span></div>
                                    </div>
                                </div>```

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In your blogpost view try getting comments manually and pass them in the context, instead of calling a class method inside the template. Template purpose is to display the buisness logic, not write or define it.

def blogpost(request, year, month, day, post):
    category_count= get_category_count()
    latest = Blogpost.objects.order_by('-publish')[0:4]
    post = get_object_or_404(Blogpost, slug=post)
    comments = post.comments.all() # here
    form = CommentForm(request.POST or None)
    if request.method == "POST":
        if form.is_valid():
            form.instance.user = request.user
            form.instance.post = post
            form.save()
            return redirect('.')
    context = {'post':post,
    'latest': latest,
    'category_count': category_count,
    'form': form,
    'comments': comments
    }
    return render(request, 'blog/blogpost.html', context)

then in your template just use:

{% for comment in comments %}
    {{ comment }}
{% endfor %}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...