1

Hi i need to check the 10th of each month in my django template file , can anybody tell me how can i check this accentually i need to show some data before the 10th of each month and hide that after 10th

4

1 回答 1

5

A few things to understand:

  1. Django's templating language isn't really designed around "real" programming. At it's core, it's just building strings.
  2. It doesn't support real "expressions".
  3. …but it does support basic conditionals and loops.
  4. So while you can check if a value is equal to or greater than or less than another value, you can't do much more than that.
  5. Unless you use a filter or a custom template tag.
  6. Filters can transform values from one thing to another.
  7. Template tags can do way more complicated things, that are beyond the scope of this question.
  8. While either a filter or a custom template tag could get where you want to go, they'd be overkill.

So, in my opinion, the easiest way to do this would be to:

  1. Calculate the day of the current date in your view.
  2. Pass that value to your template.
  3. Do a simple "if greater than" check on the passed in value against the number 10.

So, our view would look something like:

def sample_view(request, *args, **kwargs):
    from datetime import date
    current_date = date.today()
    current_day = int(current_date.day) # force a cast to an int, just to be explicit
    return render_to_response("template", {'day_of_the_month': current_day })

And in our template we would do:

{% if day_of_the_month > 10 %}
    <!-- Stuff to show after the 10th -->
{% else %}
    <!-- Stuff to show before the 10th -->
{% endif %}

This does expose stuff to your template you might be hiding based on the date for security reasons. You should never hide secure things in a template based on an if/then check.

If you need to do additional checks, you could just pass in current_date, and check current_date.day against the number 10 instead of specifically passing in that day. It'd be less explicit, but more generic and flexible.

于 2013-03-14T07:18:26.107 回答