Django多对多访问两种模型

时间:2012-12-12 22:44:47

标签: python django django-models many-to-many django-views

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

models.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',)

views.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})

urls.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 %}

2 个答案:

答案 0 :(得分:2)

您传递给模板的变量称为post而不是post_list

答案 1 :(得分: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})