Django for Designers: Difference between revisions

imported>Aldeka
 
==== Modify views and templates to use model data ====
 
Let's edit our views and templates so they use real bookmark data from our database!
 
First, let's add a bit more fake data to our database.
 
TODO: fake bookmark population script
 
Then, we'll need to have our view import the bookmark model and send the data to the view.
 
<source lang="python">
from django.shortcuts import render_to_response
from bookmarks.models import Bookmark
 
 
def index(request):
bookmarks = Bookmark.objects.all()
context = {
'bookmarks': bookmarks
}
return render_to_response('index.html', context)
</source>
 
Wait! We don't actually want to load every bookmark in our database when we go to the front page. If we have lots of bookmarks, that will get slow and unwieldy quickly.
 
Instead, let's show the 10 most recent bookmarks:
 
<source lang="python">
def index(request):
bookmarks = Bookmark.objects.all().order_by('-timestamp')[:10]
context = {
'bookmarks': bookmarks
}
return render_to_response('index.html', context)
</source>
 
We also want our tag view to show real bookmarks. We only want to show bookmarks that have been tagged with the given tag. So we can write:
 
<source lang="python">
from django.shortcuts import render_to_response
from bookmarks.models import Bookmark, Tag
 
 
[...]
 
def tag(request, tag_name):
tag = Tag.objects.get(slug=tag_name)
bookmarks = tag.bookmarks.all()
context = {
'tag': tag,
'bookmarks': bookmarks,
}
return render_to_response('tag.html', context)
</source>
 
TODO: get_object_or_404
 
(do something runserver related here?)
Anonymous user