2015-04-06 108 views
1

我正在嘗試爲博客帖子創建基於用戶的實例,但我所有的嘗試都不斷顯示每個​​用戶的所有帖子。例如,我發佈一個新帖子併發布它。所有職位顯示爲每一位用戶,而不是僅在用戶已登錄用戶和對象外鍵

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') 

回答

3

您需要過濾掉Post S其中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') 
+0

謝謝!它很好地工作。 – hokatvcu