読者です 読者をやめる 読者になる 読者になる

牌語備忘録 -pygo

あくまでもメモです。なるべくオフィシャルの情報を参照してください。

牌語備忘録 -pygo

Django でユーザごとに一覧表示させるのに汎用ビュー使う場合と使わない場合のメモ

Python Django

(python2.7, django1.5)

models.py

from django.db import models
from django.contrib.auth.models import User

class Say(models.Model):
    message = models.CharField(max_length=255)
    date_created = models.DateTimeField(auto_now_add=True)
    user = models.ForeignKey(User)

    def __unicode__(self):
        return self.message

views.py

from django.shortcuts import render_to_response
from django.views.generic import ListView

from says.models import Say

def index(request):
    says = Say.objects.filter(user=request.user).order_by('-date_created')
    return render_to_response(
        'says/index.html', {
            'says': says,
        })

class SayListView(ListView):
    context_object_name = "says"
    template_name = "says/index.html"

    def get_queryset(self):
        return Say.objects.filter(user=self.request.user).order_by('-date_created')

urls.py

from django.conf.urls import patterns, url
from says.views import SayListView

urlpatterns = patterns('says.views',
                       url(r'^$', 'index'),
                       url(r'^genericview$', SayListView.as_view()),
)