How can I pass two models to a class based generic view

后端 未结 2 559
北恋
北恋 2021-01-28 19:41

I have an app called \"blog\" that has a model called \"Entry\". I use a class based generic to view this Entry and I am happy with this.

Now, along comes another app ca

2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-28 20:29

    Since you're using Django's class based views, just extend the class(es) you're using.

    For the DetailView, in your app's views.py file, add your new view class:

    from django.views.generic import DetailView
    from blog.models import Entry
    from eventapp.models import Event
    
    class BlogEntryView(DetailView):
        """Extends the detail view to add Events to the context"""
        model = Entry
    
        def get_context_data(self, **kwargs):
            context = super(BlogEntryView, self).get_context_data(**kwargs)
            context['events'] = Event.objects.all()
            return context
    

    We're leaving out the queryset and the slug field name because given the model name the DetailView class defaults to the Entry.objects.all() queryset, and 'slug' is the default slug field name. If you want to explicitly declare those, then add them right under the model assignment.

    Then update your urls.py file like so:

    from blog.views import BlogEntryView
    
    urls = patterns('',
        url(r'^$', ArchiveIndexView.as_view(
            model=Entry, paginate_by=5,
            date_field='pub_date',template_name='homepage.html'),
        ),
        url(r'^(?P\d{4})/(?P[a-z]{3})/(?P\w{1,2})/(?P\w+)/$', 
            BlogEntryView.as_view()),
     )
    

    This is detailed in the class based generic view documentation, to boot.

提交回复
热议问题