ITの隊長のブログ

ITの隊長のブログです。Rubyを使って仕事しています。最近も色々やっているお(^ω^ = ^ω^)

Django勉強中

スポンサードリンク

Django勉強中。

とりあえず途中までをメモ。

MVC

CakePHPなどの他MVCフレームワークを使うとちょっとこんがらがる。

CakePHP

  • Model
  • View
  • Controller

Django

  • Model
  • Template(CakeでいうView)
  • View (CakeでいうController)

Model.objects.get()で、取得できずにExceptionが発生した場合

  try:
    post = Post.objects.get(id=post_id)
  except:
    return redirect('/')

こんな感じでtry ~ exceptをはればいいと思う。

ページネーションを使いたい

from django.views.generic.list import ListView

...

class PostList(ListView):
  context_object_name = 'posts'
  template_name = 'posts/list.html'
  paginate_by = 2

  def get(self, request, *args, **kwargs):
    posts = Post.objects.all().order_by('id')
    self.object_list = posts
    context = self.get_context_data(object_list=self.object_list, post=posts)
    return self.render_to_response(context)

ListViewを継承(?)してあげて、必要な情報を用意すればおk

あと、チュートリアルじゃ物足りん+情報が少ない気がする(多分)

本買おうかな。。。