0

I have a view in django that has a filter that uses two dates. I want to calculate the dates in a separate function to tidy it up a bit and return them to the view.

def index(request):
    function = month()
    objectcount = Entry.objects.filter(entrydate__range=(function[0], function[1])).count() #bleurgh!
    context = {
        "objectcount": objectcount,
    }
    return render(request, 'entry/index.html', context)

def month():
    today = datetime.datetime.now().date()
    first_of_month = "{}-{}-01".format(today.year, today.month)
    last = calendar.monthrange(today.year, today.month)[1]
    last_of_month = "{}-{}-{}".format(today.year, today.month, last)

    return first_of_month, last_of_month

This works fine, but I have to access the variables using function[0] and function[1].

How can I pass these variables so they are accessed from the index view using names - like first_of_month and last_of_month?

1
  • pass them as tuples return (first_of_month, last_of_month) Commented Mar 30, 2017 at 9:52

2 Answers 2

1

Maybe you write like this

def month():
    today = datetime.datetime.now().date()
    first_of_month = "{}-{}-01".format(today.year, today.month)
    last = calendar.monthrange(today.year, today.month)[1]
    last_of_month = "{}-{}-{}".format(today.year, today.month, last)
    resp_data ={"first_of_month":first_of_month,"last_of_month":last_of_month}
    return resp_data

function["first_of_month"] function["last_of_month"]

Sign up to request clarification or add additional context in comments.

Comments

1
  1. Pass them as tuples

    return (first_of_month, last_of_month)

and access it via index.

  1. pass them as a dictionary like

    var ={"a":a,"b":b} return var

Comments

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.