简体   繁体   中英

Assigning a datetime object as the url parameter

I want to give the value of Datetime type to url as parameter using date filter.

My url must be such: /account/detail-of-cash-flow/2020-8-10

This command: {{item.date_field|date:'Ym-d'}} = '2020-8-10'. But, not working when i this commands implement to template url.

template.html

{% for item in cash_flow_data %}

    <tr class='clickable-row' data-href="{%  url 'account:detail_of_cash_flow' item.date_field|date:'Y-m-d' %}">     
        <td>{{ item.date_field }}</td>
        <td>{{ item.EUR }}</td>
        <td>{{ item.USD }}</td>
        <td>{{ item.GBP }}</td>
        <td>{{ item.TRY }}</td>
    </tr>

{% endfor %}

urls.py

app_name = "account"
urlpatterns = [
    path('daily-cash-flow/', views.daily_cash_flow, name = "daily_cash_flow"),
    path('detail-of-cash-flow/<slug:slug>/', views.detail_of_cash_flow, name = "detail_of_cash_flow")
]

I hope I was able to explain my problem.

in your item model add method which will return format you need

class ItemModel(models.Model):
    ...
    def get_url_date(self):
        return self.date_field.strftime("%Y-%m-%d")

and then in template you can use

<a href="{%  url 'account:detail_of_cash_flow' item.get_url_date %}">link</a>

upd: according to your context you have several variants

  1. update your context data
context_flow_data = [ { 'url_date': item_data['date_field'].strftime("%Y-%m-%d"), 'date': item_data['date_field'], 'USD': item_data['USD'], 'EUR': item_data['EUR'], 'GBR': item_data['GBR'], } for item_data in cash_flow_data ]

and then provide this data to your context and in template use

<a href="{%  url 'account:detail_of_cash_flow' item.url_date %}">link</a>

second variant: you can add line

urlpatterns = [
    ...
    path('detail-of-cash-flow/', views.detail_of_cash_flow, name = "detail_of_cash_flow")
    ...
]

and then in template use

<a href="{%  url 'account:detail_of_cash_flow' %}{{item.date_field|date:'Y-m-d'}}/">link</a>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM