我有一个称为Post的模型。我希望每个用户都可以看到Post中的数据。
我是Django的新手。该应用是根据Django for Girls教程创建的。后来我增加了对用户注册的支持。
models.py:
from django.conf import settings
from django.db import models
from django.utils import timezone
class Post(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
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
from django.utils import timezone
from .models import Post
from .forms import PostForm
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import redirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth import login, authenticate
@login_required
def post_list(request):
posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
return render(request, 'blog/post_list.html', {'posts': posts})
模板示例(post_list.html):
{% for post in posts %}
<div class="post">
<div class="date">
<p>published: {{ post.published_date }}</p>
</div>
<h1><a href="{% url 'post_detail' pk=post.pk %}">{{ post.title }}</a></h1>
<p>{{ post.text|linebreaksbr }}</p>
</div>
{% endfor %}
答案 0 :(得分:2)
将您的过滤器更改为按用户以及发布日期进行过滤:
posts = Post.objects.filter(
published_date__lte=timezone.now(),
author=request.user
).order_by('published_date')
答案 1 :(得分:-1)