我正在尝试显示我之前工作的post.html
内的模型中的数据,但现在由于某些原因我无法理解。
urls.py
urlpatterns = [
path('', ListView.as_view(
queryset=Tutorials.objects.all().order_by("-date")[:25],
template_name="tutorials/blog.html"
)),
path('<int:pk>', DetailView.as_view(
model=Tutorials,
template_name="tutorials/post.html")),
]
blog.html
{% block python %}
{% for Tutorials in object_list %}
{% if Tutorials.categories == "pythonbasics" %}
<a href="/tutorials/{{ Tutorials.id }}"><h1>{{ Tutorials.title }}</h1></a>
<br>
Created On : {{ Tutorials.date|date:"Y-m-d" }}
{% endif %}
{% endfor %}
{% endblock %}
post.html
{% block content %}
<h3>{{ Tutorials.title }}</h3>
<h6> on {{ Tutorials.datetime }}</h6>
<div class = "code">
{{ Tutorials.content|linebreaks }}
</div>
{% endblock %}
答案 0 :(得分:2)
您应该在模板中使用object
名称:
{% block content %}
<h3>{{ object.title }}</h3>
<h6> on {{ object.datetime }}</h6>
<div class = "code">
{{ object.content|linebreaks }}
</div>
{% endblock %}
或者,如果您想使用Tutorial
变量,则需要将context_object_name=Tutorials
传递给视图:
path('<int:pk>', DetailView.as_view(
model=Tutorials,
template_name="tutorials/post.html",
context_object_name='Tutorials')),
答案 1 :(得分:1)
加上@ neverwalkaloner的答案。
您可以使用Set lastA = cells(rows.count, "A").end(xlup)
set R = range("A1", lastA)
range("N2", cells(lastA.row, "N")).value = ...
或object
的原因是您继承context_object_name
。
在DetailView
中,它有DetailView
方法。
get_object()
它将返回模型对象,您也可以覆盖此方法。
def get_object(self, queryset=None):
"""
Return the object the view is displaying.
Require `self.queryset` and a `pk` or `slug` argument in the URLconf.
Subclasses can override this to return any object.
"""
# Use a custom queryset if provided; this is required for subclasses
# like DateDetailView
if queryset is None:
queryset = self.get_queryset()
# Next, try looking up by primary key.
pk = self.kwargs.get(self.pk_url_kwarg)
slug = self.kwargs.get(self.slug_url_kwarg)
if pk is not None:
queryset = queryset.filter(pk=pk)
# Next, try looking up by slug.
if slug is not None and (pk is None or self.query_pk_and_slug):
slug_field = self.get_slug_field()
queryset = queryset.filter(**{slug_field: slug})
# If none of those are defined, it's an error.
if pk is None and slug is None:
raise AttributeError("Generic detail view %s must be called with "
"either an object pk or a slug."
% self.__class__.__name__)
try:
# Get the single item from the filtered queryset
obj = queryset.get()
except queryset.model.DoesNotExist:
raise Http404(_("No %(verbose_name)s found matching the query") %
{'verbose_name': queryset.model._meta.verbose_name})
return obj
中的get()
方法,
DetailView
如您所见,它将def get(self, request, *args, **kwargs):
self.object = self.get_object()
context = self.get_context_data(object=self.object)
return self.render_to_response(context)
定义为self.object
,因此您可以在self.get_object()
内使用self.object
。
最后,由于DetailView
,您可以在模板中使用object
。
get_context_data()
基本上将“对象”添加到上下文中,因此您可以使用它。
DetailView
CBV确实有一点学习曲线,但是当你看到django源代码并阅读有关文档时,它很容易理解。
+我强烈推荐ccbv.co.kr - 您可以看到CBV继承的视图和混合,以及它的方法。