Django:从URL清除值的位置?

时间:2018-05-16 09:49:25

标签: django django-class-based-views

我想写一个基于类的视图,我想清理一部分URL:

网址如下所示:

r'^some-date/(?P<date>\d\d\d\d-\d\d-\d\d)/view'

我应该使用哪种方法将字符串(例如“2018-12-31”)“清理”到python datetime对象?

2 个答案:

答案 0 :(得分:3)

在django2.0中我们可以使用路径转换器。

  

custom_path_converter.py

from datetime import datetime

class DatePathConverter:
    regex = '\d\d\d\d-\d\d-\d\d'

    def to_python(self, date_str):
        date = datetime.strptime(value, "%Y-%m-%d").date()
        return date

    def to_url(self, date):
        return date.strftime("%Y-%m-%d")
  

urls.py

from django.urls import register_converter, path
from .views import views
register_converter(DatePathConverter, 'date')

urlpatterns = [
    # ....
    path('some-date/<date:date>/', views.some_view)
    # ....
]

阅读:https://learnbatta.com/blog/custom-path-converters-in-django-17/
官方文件:https://docs.djangoproject.com/en/2.0/topics/http/urls/#registering-custom-path-converters

答案 1 :(得分:0)

def clean_date(request, date):
    datetime_object = datetime.strptime(date, '%b %d %Y %I:%M%p')