2

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

1 Answer 1

6

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your answer but I don't understand why the mixin should inherit from the object I'm trying to write a view for. What if I want to use the YourListView or YorDetailView classes to render other objects?
My mistake, I thought that with object you meant my example object not an actual python object, I get it now, I created the Mixin and it is working fine. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.