Multiple models generic DetailView to template

前端 未结 1 1713
粉色の甜心
粉色の甜心 2021-01-06 11:25

I have 2 models and I got the IndexView working properly using the get_context_data method. However my DetailView using the same techn

相关标签:
1条回答
  • 2021-01-06 11:57

    Explanation of why you can't use one view for both models

    A DetailView is meant to display details about an object from one model. It's fine to include extra context, but the view isn't designed to handle two possible models.

    The example from the docs is showing the details for one publisher, and displaying all the books at the same time.

    Your DetailView lets you show the details for one CharacterSeries, and display all of the CharacterUniverse at the same time.

    However, you cannot use that same view to display details for one CharacterUniverse. You need a different view to display details for one CharacterUniverse

    Solution

    Therefore, you need two different detail views, one for each model.

    You need a distinct url for each view. Otherwise, the request will always match the first regex (in this case series_detail. The following would work.

    url(r'^series/(?P<pk>[0-9]+)/$', views.SeriesDetail.as_view(), name='series_detail'),
    url(r'^universe/(?P<pk>[0-9]+)/$', views.UniverseDetail.as_view(), name='universe_detail'),
    
    0 讨论(0)
提交回复
热议问题