user1664820
user1664820

Reputation: 313

Django class based generic views and inheritance

So I'm writing this application and using the generic views objects ListView and ObjectView.

I've overridden the method get_context_data on both to be able to add the same extra context (no related to the object) on both cases.

Now I have two classes, one extending Listview and the other extending DetailView both with identical get_context_data methods.

While this is working fine is really hurting to see, is there a parent class that I can override the get_context_data from that will make the ListView and DetailView inherit the new get_context_data? It would look much nicer that way :)

Thank you.

X

Upvotes: 2

Views: 3015

Answers (1)

jondykeman
jondykeman

Reputation: 6272

If how you are wanting to override the get_context_data are the same I would use a mixin.

class CommonMixinExample(object):

    def get_context_data(self, **kwargs):
        # do stuff in here
        return super(CommonMixinExample, self).get_context_data(**kwargs)

class YourListView(CommonMixinExample, ListView):
    # other code

class YourDetailView(CommonMixinExample, DetailView):
    # other code

Upvotes: 6

Related Questions