django认证和发布错误,使用request.user.is_autheticated时获取不同的用户帖子

时间:2018-03-28 19:40:57

标签: django-models django-templates django-views django-authentication

以下是我的代码:

  from django.db import models
  from django.utils import timezone
  from django.contrib.auth.models import User
  from django.urls import reverse
  from django.conf import settings


class Post(models.Model):
 STATUS_CHOICES = (('draft', 'Draft'),('published', 'Published'),)
 title = models.CharField(max_length=250)
 slug = models.SlugField(max_length=250,unique_for_date='publish',blank=True)
 author = models.ForeignKey(User, related_name='blog_posts',on_delete=models.CASCADE)
 body = models.TextField()
 publish = models.DateTimeField(default=timezone.now)
 created = models.DateTimeField(auto_now_add=True)
 updated = models.DateTimeField(auto_now=True)
 status = models.CharField(max_length=10,choices=STATUS_CHOICES,default='draft')
 image=models.FileField(null=True,blank=True)


 class Meta:
     ordering = ('-publish',)

 def get_absolute_url(self):
    return reverse('post_detail', args=[str(self.id)])


 def __str__(self):
     return self.title

以下是views.py代码,

    from django.shortcuts import render
    from django.http import HttpResponse
     from django.views.generic import 
     TemplateView,ListView,DetailView,CreateView
     from django.contrib.auth.mixins import LoginRequiredMixin
     from .models import Post
     from .forms import PostForm
     from django.contrib.auth.models import User






class HomePageView(ListView):

model = Post
template_name = 'home.html'


def get_context_data(self, **kwargs):
    # Call the base implementation first to get a context
    context = super().get_context_data(**kwargs)
    # Add in a QuerySet of all the books
    context['deeppost'] = 
Post.objects.filter(author=self.request.user.is_authenticated)
    return context





 class AboutPageView(TemplateView):
  template_name = 'about.html'




 class BlogDetailView(DetailView):
  model = Post
  template_name = 'post_detail.html'


 class PostNewView(LoginRequiredMixin,CreateView):
  template_name = 'new_post.html'
  form_class = PostForm




  def form_valid(self, form):
      form.instance.author = self.request.user
      return super().form_valid(form)

以下是我的HTML

-->
 {% extends 'base.html' %}

 {% block content %}

<h1>Homepage.</h1>

 <ul>
  {% if user.is_authenticated %}
 {% for post in deeppost %}
 <li>{{post.title}}</li></a><p>{{post.body}}</p><p>
  {% if post.image %}<img src="{{post.image.url}}" width="100" height="100">
  {% endif %}</p>Created by-{{post.author}}

  {% endfor %}
  <h2><a href="{% url 'new_post' %}">Create a New Post </a></h2>
  {% else %}
  <p>You are not logged in. Please goto the login Page by clicking on the 
    login 
   link above </p>

 {% endif %}
 </ul>-
 {% endblock %}

问题是我只有1个用户,超级用户和testingaccount,现在在我添加文件字段并进行迁移之前,它是工作文件,只有相关用户创建的帖子在我进行迁移后才显示超级用户正在显示,我不明白这个问题

0 个答案:

没有答案