В этой ситуации я создаю блог, и в этом блоге я создаю страницу «Мои сообщения», и дело в том, что если пользователь не создал сообщение, я хочу, чтобы он сказал сообщение "Вы еще не написали ни одной публикации", у меня проблемы с логом c в 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,))
Я был бы очень признателен за вашу помощь и спасибо заранее!