【问题标题】:Assigning a datetime object as the url parameter将 datetime 对象分配为 url 参数
【发布时间】:2020-10-08 09:33:53
【问题描述】:

我想使用日期过滤器将 Datetime 类型的值作为参数提供给 url。

我的网址必须是这样的:/account/detail-of-cash-flow/2020-8-10

此命令:{{item.date_field|date:'Y-m-d'}} = '2020-8-10'。但是,当我将此命令实现到模板 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")
]

我希望我能够解释我的问题。

【问题讨论】:

    标签: python python-3.x django django-templates


    【解决方案1】:

    在您的项目模型中添加方法,该方法将返回您需要的格式

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

    然后可以在模板中使用

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

    更新: 根据您的上下文,您有几个变体

    1. 更新您的上下文数据
    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 
    ]
    

    然后将此数据提供给您的上下文 并在模板中使用

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

    第二种变体: 你可以添加行

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

    然后在模板中使用

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

    【讨论】:

    • 此建议无效。我得到:没有找到参数'('',)'的'detail_of_cash_flow'的反向。尝试了 1 种模式:['account/detail\\-of\\-cash\\-flow/(?P[-a-zA-Z0-9_]+)/$']
    • {{ item.get_url_date }} = null
    • 那么如果 date_field 为空,你想要什么 url?
    • 哦,对不起。现在记得。我的上下文数据:paste.ubuntu.com/p/ZDbV9dmVSG
    猜你喜欢
    • 2019-02-16
    • 2014-05-05
    • 2020-04-18
    • 2014-03-28
    • 1970-01-01
    • 1970-01-01
    • 2017-03-04
    • 2017-02-24
    • 1970-01-01
    相关资源
    最近更新 更多