【问题标题】:If there are no Posts displayed, how can I put a message?如果没有显示帖子,我该如何发布消息?
【发布时间】:2020-08-07 06:29:14
【问题描述】:

在这种情况下,我正在创建一个博客,在这个博客中,我正在创建一个“我的帖子”页面,问题是如果用户尚未创建帖子,我希望它说出消息“你还没有写任何帖子”,我在 html 中的逻辑有问题,我试图使用 {% if post %},但它不起作用,这是代码:

my_posts.html

{% extends "app1/base.html" %}
{% block body_block %}


<div class="container">
<h1>Post</h1>
{% for post in object_list %}
{% empty %}
    <h1>You have not written any posts yet!</h1>
{% if user.is_authenticated %}
{% if user.id == post.author.id %}
    <li><a href="{% url 'app1:article-detail' post.pk %}">{{post.title}}</a> -
    {{post.author}} - <small>{{post.post_date}}</small> - <small> category : <a href="{% url 'app1:category' post.category|slugify %}">{{post.category}}</a> - </small>
    <small><a href="{% url 'app1:updatepost' post.pk %}">Edit</a></small><small>
    <a href="{% url 'app1:deletepost' post.pk %}">- Delete</a>  
    </small></li>
    {{post.snippet}}
    {% endif %}
    {% endif %}

    
    



{% endfor %}
</div>

{% endblock %}

views.py

from django.shortcuts import render, get_object_or_404
from django.contrib.auth import authenticate, login, logout
from django.urls import reverse, reverse_lazy
from .forms import  PostForm, PostUpdateForm
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from .models import Post, Category
from django.http import HttpResponseRedirect



# Create your views here.
def index(request):
    return render(request, 'app1/index.html')
    
def LikeView(request, pk):
    post = get_object_or_404(Post, id=request.POST.get('post_id'))
    liked = False
    if post.likes.filter(id = request.user.id).exists():
        post.likes.remove(request.user)
        liked = False
    else:
        post.likes.add(request.user)
        liked = True
    
    return HttpResponseRedirect(reverse('app1:article-detail', args = [str(pk),]))


class PostView(ListView):
    model = Post
    template_name = 'app1/post.html'
    ordering = ['-post_date']

    def get_context_data(self, *args, **kwargs):
        cat_menu = Category.objects.all()
        context = super(PostView, self).get_context_data(*args, **kwargs)
        context["cat_menu"] = cat_menu
        return context

def CategoryView(request, cats):
    category_posts = Post.objects.filter(category=cats.replace('-', ' '))
    return render(request, 'app1/categories.html', {'cats':cats.title().replace('-', ' '), 'category_posts': category_posts})

def CategoryListView(request):
    cat_menu_list = Category.objects.all()
    return render(request, 'app1/category_list.html', {"cat_menu_list":cat_menu_list})

class ArticleDetailView(DetailView):
    model = Post
    template_name = 'app1/article_details.html'

    def get_context_data(self, *args, **kwargs):
        
        context = super(ArticleDetailView, self).get_context_data(*args, **kwargs)
        stuff = get_object_or_404(Post, id = self.kwargs['pk'])
        liked = False
        if stuff.likes.filter(id = self.request.user.id).exists():
            liked = True
        total_likes = stuff.total_likes()
        context["total_likes"] = total_likes
        context["liked"] = liked
        return context

class AddPostView(CreateView):
    model = Post
    form_class = PostForm
    template_name = 'app1/createpost.html'
    #fields = '__all__'

class UpdatePostView(UpdateView):
    model = Post
    form_class = PostUpdateForm
    template_name = 'app1/update_post.html'

class DeletePostView(DeleteView):
    model = Post
    template_name = 'app1/delete_post.html'
    success_url = reverse_lazy('index')

class AddCategoryView(CreateView):
    model = Category
    template_name = 'app1/add_category.html'
    fields = '__all__'
    success_url = reverse_lazy('app1:Post')

class MyPostsView(ListView):
    model = Post
    template_name = 'app1/my_posts.html'

models.py

from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse
from datetime import datetime, date
from ckeditor.fields import RichTextField
# Create your models here.


class Category(models.Model):
    name = models.CharField(max_length= 255)
    
    def __str__(self):
        return self.name 
    
    def get_absolute_url(self):
        return reverse('index')

class Profile(models.Model):
    user = models.OneToOneField(User, null = True, on_delete=models.CASCADE)
    bio = models.TextField()
    profile_pic = models.ImageField(null = True, blank = True, upload_to = "images/profile/")
    website_url = models.CharField(max_length= 255, blank = True, null = True)
    facebook_url = models.CharField(max_length= 255, blank = True, null = True)
    twitter_url = models.CharField(max_length= 255, blank = True, null = True)
    instagram_url = models.CharField(max_length= 255, blank = True, null = True)
    pinterest_url = models.CharField(max_length= 255, blank = True, null = True)

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

class Post(models.Model):
    title = models.CharField(max_length= 255)
    header_image = models.ImageField(null = True, blank = True, upload_to = 'images/')
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    body = RichTextField(blank = True, null = True)
    #body = models.TextField()
    post_date = models.DateField(auto_now_add=True)
    category = models.CharField(max_length=255, default='coding')
    snippet = models.CharField(max_length=255)
    likes = models.ManyToManyField(User, related_name = 'blog_posts')

    def total_likes(self):
        return self.likes.count()

    def __str__(self):
        return self.title + ' | ' + str(self.author)
    
    def get_absolute_url(self):
        return reverse('app1:article-detail', args=(self.id,))
        

非常感谢您的帮助,并提前致谢!

【问题讨论】:

    标签: python django authentication post blogs


    【解决方案1】:

    你可以在for循环中使用{% empty %}标签。

    {% for post in object_list %}
    ...
    {% empty %}
       <h1>You have not written any posts yet!</h1>
        
    {% endfor %}
    

    或者您可以像这样在模板中简单地使用if else

    {% if object_list %}
    {% for post in object_list %}
        ...
    {% endfor %}
    {% else %}
           <h1>You have not written any posts yet!</h1>
    {% endif %}
    

    【讨论】:

    • 我必须把它放在 ifs 之外吗?因为它要求一个 else 或 elif
    • 我更新了,你可以看看我是怎么写的,但是还是不行
    • 消息仍然没有显示,我更新了帖子中的代码,以便您查看是否有错误
    • 模板中有这么多条件。最好在视图 尽可能多地而不是模板中编写逻辑。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-14
    • 2019-08-05
    • 2020-08-23
    • 1970-01-01
    • 2013-01-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多