[Fixed]-How to add custom benefit in django-oscar?

0đź‘Ť

âś…

First of all you will need to fork the offer app from oscar with the below command.

./manage.py oscar_fork_app offer apps/shop

One can add custom benefit in the benefits.py file. Below benefit class will give “cheapest product from the selected range with 50% off”.

class NewCustomBenefit(benefits.Benefit):
    description = "Cheapest product from range is 50% off"

    @property
    def name(self):
        return self.description

    class Meta:
        app_label = 'offer'
        proxy = True
        verbose_name = _("Buy 1 get 50% off")
        verbose_name_plural = _("Buy 1 get 50% off")

    def apply(self, basket, condition, offer):
        line_tuples = self.get_applicable_lines(offer, basket, range=condition.range)
        if not line_tuples:
            return results.ZERO_DISCOUNT

        # Cheapest line gives 50% off on second product
        discount, line = line_tuples[0]
        discount /= 2
        apply_discount(line, discount, 1)

        affected_lines = [(line, discount, 1)]
        condition.consume_items(offer, basket, affected_lines)
        return results.BasketDiscount(discount)

    def __unicode__(self):
        return unicode(self.name)

Now, next step is to available this benefit while adding offer from the dashboard. You will have option to select predefined benefit/incentive from the the dropdown.

enter image description here

Now, to available this benefit here You’ll need to register our custom benefit from the admin panel. So, follow below screenshot.
You gotta enter the path to the custom benefit class in the custom class field. Other-than that keep everything blank as you’ll add those info from dashboard while creating offer.

Once you save this, you’ll have your benefit in the dropdown as shown in the first screenshot.

enter image description here

It works.! Ask If have any other query.

👤Jay Modi

1đź‘Ť

I know kinda old thread but you need to use create_benefit (https://django-oscar.readthedocs.io/en/3.0.0/howto/how_to_create_a_custom_benefit.html)

…your code

from oscar.apps.offer.custom import create_benefit

create_benefit(your_benefit_custom_class)

…more code

( Does not necessary needs to be in views.py , models.py ..etc)

!!!CAREFUL!!!

If it is get called by somewhere from your code again it will reinitialize it and you will have the same custom benefit more than once so either call it from shell or create an if condition to get called .

( Answer to why is not my custom benefit showing )

👤Solorak

Leave a comment