Hi
You can get at components passed in the url in views like this
class AuthorView(DetailView):
model = Author
def get_context_data(self, **kwargs):
context = super(AuthorView, self).get_context_data(**kwargs)
slug = self.kwargs['slug']
So if you are adding a book you can do something similar
class BookCreate(CreateView)
model = Book
def get_initial(self):
initials = super(BookCreate, self).get_initial()
initials['author'] = self.kwargs['slug']
and if you want to return to the author after creating the book
def get_success_url(self):
slug = self.kwargs['slug']
return reverse('author', kwargs={'slug': slug})
Although you can build up a complicated url like this
r'^author/(?P<aid>\d+)/book/(?P<pk>\d+)/edit$',
view=BookEdit.as_view(),
name='bookedit'),
and still access the url components like
aid = self.kwargs['aid']
pk = self.kwargs['pk']
it means often over-riding get_queryset, get_context_data, etc just to get
at the components to reconstruct urls so you can navigate between
views and of course the url becomes fragile if you can change the author of
a book or a book has several authors
I prefer to avoid this and edit books under their own url tree like
r'^book/(?P<pk>\d+)/edit$',
view=BookEdit.as_view(),
name='bookedit'),
This keeps the view much simpler.
You can still easily move between the two models or include related
material using "related_names" on the model's ForeignKey
so if in models.Book we had
author = models.ForeignKey('Author', related_name='books')
in your Author templates you can do
{% for book in author.book_set.all %}
{% end for %}
or just
{{ author.book_set.count }}
https://docs.djangoproject.com/en/1.5/topics/db/queries/#backwards-related-objects
--
Drew Ferguson
AFC Commercial
http://www.afccommercial.co.uk