[Answer]-Django using timedelta to filter results in template

1👍

✅

views.py

class NextSubscription(View):
    def get(self, request):
        try:
            return Subscription.objects.filter(start_date__gt=date.today()).order_by("start_date")[0]
        except IndexError:
            raise Exception("No Next Subscription Found")

class CurrentSubscription(View):
    def get(self, request):
        try:
            return Subscription.objects.filter(start_date__lt=date.today()).order_by("-start_date")[0]
        except IndexError:
            raise Exception("No Current Subscription Found")

0👍

I think it’s better to put this in your forms logic rather than views.
I presume there is also an Issue model, something like this:

class Issue(models.Model):
    issue_date = models.DateField()
    ....

Upon saving your Subscription, your save() should do something like this:

forms.py

from models import Subscription
from django import forms
class SubscriptionForm(forms.ModelForm):
    def save(self, commit=True):
        instance = super(SubscriptionForm, self).save(commit=False)
        if instance.start_from_next:  # You should add a start_from_next boolean field to know if user wants to start from previous or next issue
            the_issue = Issue.objects.filter(issue_date__gt=date.today()).order_by("start_date")[0]
        else:
            the_issue = Issue.objects.filter(issue_date__lt=date.today()).order_by("-start_date")[0]
        instance.start_date = the_issue.start_date
        if commit:
            instance.save()
        return instance

    class Meta:
        model = Subscription

Leave a comment