简体   繁体   English

如何检查当前登录用户的 model 是否为空?

[英]How to check if the model is empty for the current logged user?

I'm trying to check if the model is empty or not to display a message in the blog, for example, if you have no posts yet, I want a message to appear that says "No posts yet", but I don't know how to tell django when the user is logged in and the model is empty, here's the code.我正在尝试检查 model 是否为空或不在博客中显示消息,例如,如果您还没有帖子,我希望显示“还没有帖子”的消息,但我没有当用户登录并且 model 为空时,知道如何告诉 django,这是代码。

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')
class MyPostsView(ListView):
    model = Post
    template_name = 'app1/my_posts.html'
    
    def post_list(request):
        var = False
        exists = Post.body.filter(user=request.user).exists()
        if exists:
            var = True
        
        else:
            var = False
        
        context = {'var':var}
        return render(request, 'app1/my_posts.html', context)
{% extends "app1/base.html" %}
{% block body_block %}


<div class="container">
<h1>Post</h1>

{% for post in object_list %}
{% 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 %}
    {% empty %}
    No Posts yet
    {% endfor %}

You filter the queryset with the logged in user by overriding the get_queryset(…) method [Django-doc] :您可以通过覆盖get_queryset(…)方法 [Django-doc]来过滤带有登录用户的查询集:

from django.contrib.auth.mixins import LoginRequiredMixin

class MyPostsView(LoginRequiredMixin, ListView):
    model = Post
    template_name = 'app1/my_posts.html'
    
    def get_queryset(self, *args, **kwargs):
        return super().get_queryset(*args, **kwargs).filter(
            user=self.request.user
        )

In the template, you can then make use of a for … empty loop [Django-doc] :在模板中,您可以使用for … empty循环 [Django-doc]

{% for post in object_list %}
    {{ post.title }}
{% empty %}
    No posts yet!
{% endfor %}

Note : You can limit views to a class-based view to authenticated users with the LoginRequiredMixin mixin [Django-doc] .注意:您可以使用LoginRequiredMixin mixin [Django-doc]将视图限制为基于类的视图,以供经过身份验证的用户使用。


Note : It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly.注意:通常最好使用settings.AUTH_USER_MODEL [Django-doc]来引用用户 model,而不是直接使用User model [Django-doc] For more information you can see the referencing the User model section of the documentation .有关更多信息,您可以查看参考文档的User model部分

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM