Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling a license-like system with Django

I'm trying to come up with a way to handle licenses for a pet-project in Django. Say I wanted customers to have to pay for a license, and that allows them to access the website up until that license expires.

Are there built-in tools to handle something like this in Django?

Right now all I can think of is creating a new "license" model, with a foreign key to my customer model and a datetime field and then extending the customer model to check whether the license is still valid:

class License(models.Model): 
    customer = models.ForeignKey(
    license_end = models.DateTimeField(default=timezone.now)

Then I would extend the customer model with this method:

def has_license(self, license):
    try:
        license = self.license.get(license=license)
    except Exception:
        return False

    return license.license_end > timezone.now()

And I suppose on each view that is restricted by a license I would have to check if customer.has_license(license): (passing their valid license object).

Though it would seem like I would be writing the same few lines over and over on each view that needs to be protected.

Would there be an easier way to set this up (or something like this)?

Though it's a bit relevant, I would also have to come up with a solution for license keys and authenticating those, that's an entirely new question so I won't include it on this question.

like image 893
Mormoran Avatar asked Nov 15 '25 05:11

Mormoran


1 Answers

You can make use of middlewares

  1. Create a middleware.py and below code

    class LicenceMiddleware:
    
     def __init__(self, get_response):
            self.get_response = get_response
            # One-time configuration and initialization.
    
    
    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.
    
        response = self.get_response(request)
    
    
        if check_date:
            return response
        else:
            return render(request, 'licence_expired.html')
    
  2. Add your middleware to settings.py middleware section

Now for each request/response it checks the licencemiddleware and returns response.

You can create one more field in model to keep track the date.

like image 167
DPS Avatar answered Nov 17 '25 17:11

DPS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!