John R Perry
John R Perry

Reputation: 4202

I have 2 views that have identical post methods, what is the best way to remain DRY

I have a real estate website that has 2 views for 2 separate pages. Each page has a form that allows you to edit the transaction details. One of the pages also allows you to do other things that require the post method.

So the views basically look like this:

class ViewOne(ListView):
    # ...
    def post(self, request, *args, **kwargs):
        # update transaction logic


class ViewTwo(ListView):
    # ...
    def post(self, request, *args, **kwargs):
        # update transaction logic
        # additional post logic

What is the best way to add the post logic that updates the transaction to each view without writing duplicate code?

Upvotes: 1

Views: 34

Answers (2)

TheSohan
TheSohan

Reputation: 438

This problem can be tackled by the use of Mixin.

A mixin is a class that defines and implements a single, well-defined feature. Subclasses that inherit from the mixin inherit this feature—and nothing else.

class TransactionLogicMixin:
    def update_transaction(self):
        # your transaction code goes here.
        

class ViewOne(ListView,TransactionLogicMixin):
    # ...
    def post(self, request, *args, **kwargs):
        # update transaction logic
        self.update_transaction()


class ViewTwo(ListView,TransactionLogicMixin):
    # ...
    def post(self, request, *args, **kwargs):
        # update transaction logic
        self.update_transaction()
        # additional post logic

Upvotes: 2

Mattia
Mattia

Reputation: 1139

If you want, you can create a common function that it's called by each POST request that you can easily test and reuse in other requests.

For example

class ViewOne(ListView):
    # ...
    def post(self, request, *args, **kwargs):
        my_beautiful_def(request, foo_bar)


class ViewTwo(ListView):
    # ...
    def post(self, request, *args, **kwargs):
        my_beautiful_def(request, foo_bar)
        # additional post logic

def my_beautiful_def(request, foo_bar):
    # do something amazing
    return foo

Upvotes: 0

Related Questions