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

后端 未结 2 558
北恋
北恋 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<year>\d{4})/(?P<month>[a-z]{3})/(?P<day>\w{1,2})/(?P<slug>\w+)/$', 
            BlogEntryView.as_view()),
     )
    

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

    0 讨论(0)
  • 2021-01-28 20:45

    As it looks to me you would like to have your events on more than one page, a context processor may be the right tool for you. It should allow you to access a queryset of events within the context of every template:

    from eventapp.models import Event
    
    def event_provessor(request):
        return {'events': Event.objects.all()}    
    

    Because of the queryset's laziness you don't have to be afraid to hit the database if you don't need the list, the query is only run if you would iterate over events.

    Of course you could also eg. subclass the views and add the events there to the context, but if more than one view is affected a context processor might make more sense!

    0 讨论(0)
提交回复
热议问题