0

我正在寻找使用 Django 构建一个小型“Twitter 风格”网站来处理事情,并决定尝试允许多个用户编辑每个帖子(最终基于权限)。现在我正在努力访问每个用户的帖子。下面是我的模型、视图和模板的代码,它为所有用户显示“这里没有帖子”。我希望能够显示用户拥有但似乎没有到达任何地方的所有帖子:

模型.py

from django.db import models

class User(models.Model):
    username = models.CharField(max_length = 200)
    email = models.EmailField(max_length = 75)
    password = models.CharField(max_length = 64)
    created_date = models.DateTimeField('date created')

    def __unicode__(self):
        return self.username

    class Meta:
        ordering = ('created_date',)


class Post(models.Model):
    users = models.ManyToManyField(User)
    title = models.CharField(max_length = 300)
    post = models.TextField()
    posted_date = models.DateTimeField('date created')
    votes = models.IntegerField()

    def __unicode__(self):
        return self.title

    class Meta:
        ordering = ('posted_date',)

视图.py

from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse

from users.models import User, Post

def index(request):
    latest_user_list = User.objects.order_by('username')[:5]
    context = {'latest_user_list': latest_user_list}
    return render(request, 'users/index.html', context)

def detail(request, user_id):
    user = get_object_or_404(User, pk=user_id)
    post_list = Post.objects.filter(id == user.id)  
    return render(request, 'users/detail.html', {'user': user, 'post': post_list})

网址.py

from django.conf.urls import patterns, url

from users import views

urlpatterns = patterns('',
    url(r'^$', views.index, name='index'),
    url(r'^(?P<user_id>\d+)/$', views.detail, name='detail'),
)

(模板)-detail.html

<h1>{{ user.username }}</h1>
{% if post_list %}
    <ul>
    {% for post in post_list%}
        <li>{{ post.title }}</li>
    {% endfor %}
    </ul>
{% else %}
    <p> There aint no posts here </p>
{% endif %}
4

2 回答 2

2

您传递给模板的变量称为postnot post_list

于 2012-12-12T22:48:21.067 回答
2

更改视图中列表对象的名称。

def detail(request, user_id):
    user = get_object_or_404(User, pk=user_id)
    post_list = Post.objects.filter(id == user.id)  
    return render(request, 'users/detail.html', {'user': user, 'post_list': post_list})
于 2012-12-13T01:22:48.787 回答