我正在尝试为博客帖子制作基于用户的实例,但我的所有尝试都会继续显示每个用户的所有帖子。例如,我发布一个新帖子并发布它。所有帖子都显示给每个用户,而不仅仅是登录的用户。
models.py
:
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.conf import settings
class Post(models.Model):
author = models.ForeignKey(User)
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
views.py
:
from django.shortcuts import render, get_object_or_404, redirect
from django.utils import timezone
from .models import Post
from .forms import PostForm
def post_list(request):
posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
return render(request, 'myblog/post_list.html', {'posts':posts})
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
return render(request, 'myblog/post_detail.html', {'post': post})
def post_new(request):
if request.method == "POST":
form = PostForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.author = request.user
post.save()
return redirect('myblog.views.post_detail', pk=post.pk)
else:
form = PostForm()
return render(request, 'myblog/post_edit.html', {'form': form})
def post_edit(request, pk):
post = get_object_or_404(Post, pk=pk)
if request.method == "POST":
form = PostForm(request.POST, instance=post)
if form.is_valid():
post = form.save(commit=False)
post.author = request.user
post.save()
return redirect('myblog.views.post_detail', pk=post.pk)
else:
form = PostForm(instance=post)
return render(request, 'myblog/post_edit.html', {'form': form})
def post_publish_list(request):
posts = Post.objects.all()
return render(request, 'myblog/post_publish_list.html', {'posts':posts})
def post_publish_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
return render(request, 'myblog/post_publish_detail.html', {'post': post})
def post_publish(request, pk):
post = Post.objects.get(pk=pk)
post.publish()
return redirect('myblog.views.post_list')
def post_delete(request, pk):
post = Post.objects.get(pk=pk)
post.delete()
return redirect('myblog.views.post_list')
答案 0 :(得分:3)
您需要过滤掉Post
,其中author
是当前用户。
替换:
posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
使用:
posts = Post.objects.filter(author=request.user,
published_date__lte=timezone.now()).order_by('published_date')