我在Django中創(chuàng)建了幾個date-based視圖,雖然year和month的視圖按預(yù)期運行,但沒有檢測到顯示days的視圖。例如,如果我嘗試獲取http://127.0.0.1:8000/blog/archive/2021/,或http://127.0.0.1:8000/blog/archive/2021/01視圖,則http://127.0.0.1:8000/blog/archive/2021/01/07將失敗。我知道問題一定出在urls.py配置上,但我在文檔中找不到它。我還嘗試將day_format='%d傳遞給as_view方法,但沒有任何結(jié)果。
urls.py
from django.urls import path, re_path
from blog import views
app_name = 'blog'
urlpatterns = [
# Example: /blog/
path('', views.PostListView.as_view(), name='index'),
# Example: /blog/post/ (same as /blog/)
path('post/', views.PostListView.as_view(), name='post_list'),
# Example: /blog/post/django-example/
re_path(r'^post/(?P<slug>[-\w]+)/$', views.PostDetailView.as_view(), name='post_detail'),
# Example: /blog/archive/
path('archive/', views.PostArchiveView.as_view(), name='post_archive'),
# Example: /blog/archive/2019/
path('archive/<int:year>/', views.PostYearArchiveView.as_view(), name='post_year_archive'),
# Example: /blog/archive/2019/nov/
path('archive/<int:year>/<int:month>/', views.PostMonthArchiveView.as_view(month_format = '%m'), name='post_month_archive'),
# Example: /blog/archive/2019/nov/10/
path('archive/<int:year>/<int:month>/<int:day>/', views.PostDayArchiveView.as_view(), name='post_day_archive'),
# Example: /blog/archive/today/
path('archive/today/', views.PostTodayArchiveView.as_view(), name='post_today_archive'),
]
views.py
from django.shortcuts import render
# Create your views here.
from django.views.generic import ListView, DetailView, ArchiveIndexView, YearArchiveView, MonthArchiveView, \
DayArchiveView, TodayArchiveView
from blog.models import Post
class PostListView(ListView):
model = Post
template_name = 'blog/post_all.html'
context_object_name = 'posts'
paginate_by = 2
class PostDetailView(DetailView):
model = Post
class PostArchiveView(ArchiveIndexView):
model = Post
date_field = 'modify_dt'
class PostYearArchiveView(YearArchiveView):
model = Post
date_field = 'modify_dt'
make_object_list = True
class PostMonthArchiveView(MonthArchiveView):
model = Post
date_field = 'modify_dt'
class PostDayArchiveView(DayArchiveView):
model = Post
date_field = 'modify_dt'
day_format = '%d'
class PostTodayArchiveView(TodayArchiveView):
model = Post
date_field = 'modify_dt'
post_archive_day.html
<h1>Post Archives for {{ day|date:"N d, Y" }}</h1>
<div>
<ul>
{% for post in object_list %}
<li>
{{ post.modify_dt|date:"Y-m-d" }}
<a href="{{ post.get_absolute_url }}"><strong>{{ post.title }}</strong></a>
</li>
{% endfor %}
</ul>
</div>
error
您正在構(gòu)建的URL的格式不正確,例如,它應(yīng)該是正確的格式
默認(rèn)為
month_format = '%b'
但是您使用的是
%m
,而不是月份的%b