我读过django文档,我知道django有get_next_by_foo,其中foo是日期时间,并且没有null=True。我在模型2中创建了函数get_previous和get_next,但当我在html文件中调用它时,我什么都不显示在我的型号.py 中
class Contracts(models.Model):
id=models.AutoField(primary_key=True)
contract=models.CharField(max_length=255,blank=True, null=True)
name=models.CharField(max_length=255,blank=True, null=True)
debt=models.IntegerField(blank=True, null=True)
created_at=models.DateTimeField(auto_now_add=True)
updated_at=models.DateTimeField(auto_now_add=True,blank=True)
objects=models.Manager()
class Meta:
ordering=["-created_at"]
def get_absolute_url(self):
return "/contract_detail/%s/" % self.contract
在我的视图中.html
def next_back(request, id=None):
queryset = get_object_or_404(Contracts, id=contract)
the_next = queryset.get_next_by_created_at()
the_prev= queryset.get_previous_by_created_at()
context ={
"title": queryset.title,
"instance": queryset,
"the_next" : the_next,
"the_prev": the_prev,
}
return render(request, "contract_detail.html", context)
def contract_detail(request, pk):
queryset = Contracts.objects.get(contract=pk)
context = {
"queryset": queryset,
}
return render(request, "contract_detail.html", context)
在我的网址.py
urlpatterns = [
path('admin/', admin.site.urls),
path('demo',views.showDemoPage),
#path("",views.home, name='home'),
path('customer/', views.index, name='index'),
path('customer1/', views.list_contract, name='list_contract'),
path('add_items/', views.add_items, name='add_items'),
path('search/', views.searchcontract, name='search'),
path('contract_detail/<str:pk>/', views.contract_detail, name="contract_detail"),
url(r'^export/csv/$', views.export_search_csv, name='export_search_csv'),
以及在我的contract_detail.html 中
<a href="{{ the_next.get_absolute_url }}">Next</a>
<a href="{{ the_prev.get_absolute_url }}">Previous</a>
我误解了它的概念吗?如果我这样做了,我该怎么处理?提前感谢!
修改您的URL、视图和模板。
urls.py
....
path('contract_detail/<str:contract_id>/', views.contract_detail, name="contract_detail"),
....
视图.py
def contract_detail(request, contract_id=None):
contract = get_object_or_404(Contracts, contract=contract_id)
the_next = contract.get_next_by_created_at()
the_prev = contract.get_previous_by_created_at()
context = {
"contract": contract,
"the_next" : the_next,
"the_prev": the_prev,
}
return render(request, "contract_detail.html", context)
在模板中,可以使用变量contract
来访问实例。您得到的是该模型的一个实例。因此,将其命名为queryset
没有任何意义。