get particular date in django template Django

后端 未结 1 794
走了就别回头了
走了就别回头了 2021-01-23 10:27

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 mont

1条回答
  •  星月不相逢
    2021-01-23 11:05

    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 %}
        
    {% else %}
        
    {% 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.

    0 讨论(0)
提交回复
热议问题