Search code examples
djangotemplatesviewpipdjango-context

Django template context multiple views


I'm running Idios, a profile app, and I would like to make the profiles in my app on top of idios (i.e. keep idios pip-installable, without modifying the app itself).

The problem is, the profile view is written in the idios app, using the object-oriented approach of passing context variables, and displaying that view in a template. I want the profile view to also include a list of a user's friends, managed by a separate friends app. I got a proof-of-concept by merely importing friends into Idios and updating the context with a new friend_list variable, and adding another template block to display the friends list.

So, what is the best, or most sane approach to combine both a friends list and the profile without altering the idios app? This question is basically a plea for help to really understand the MVT system in Django in a DRY way that supports reusable apps.


Solution

  • Thankfully, the mentioned app uses class-based views, and this is the benefit you get from using class-based views. To modify the context, you merely create a subclass of their profile view:

    yourapp/views.py

    from idios.views import ProfileDetailView
    
    class MyProfileDetailView(ProfileDetailView):
        def get_context_data(self, **kwargs):
            context = super(MyProfileDetailView, self).get_context_data(**kwargs)
    
            # get the list of friends and store it in a new key in `context`
    
            return context
    

    Then, just redefine the urlpattern idios uses by default in your urls.py (needs to go before the idios urlpatterns are included) and point it to your subclass instead

    Finally, to override the template idios uses by creating an idios/whatever_template.html file in your project's (or app's) templates directory. Copy the default template and modify at will. You don't have to actually touch the original source at all thanks to all the overrides Django makes available.