Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 无法在模板中显示模型中的数据_Python_Django - Fatal编程技术网

Python 无法在模板中显示模型中的数据

Python 无法在模板中显示模型中的数据,python,django,Python,Django,我试图在我的post.html中显示一个模型中的数据,这个模型以前可以工作,但现在由于某种原因无法工作 url.py urlpatterns = [ path('', ListView.as_view( queryset=Tutorials.objects.all().order_by("-date")[:25], template_name="tutorials/blog.html" )), path('<int:pk>',

我试图在我的
post.html
中显示一个模型中的数据,这个模型以前可以工作,但现在由于某种原因无法工作

url.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")),
]
urlpatterns=[
路径(“”,ListView.as_视图(
queryset=Tutorials.objects.all().order_by(“-date”)[:25],
template_name=“tutorials/blog.html”
)),
路径(“”,DetailView.as_视图(
模型=教程,
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 %}
{%block python%}
{对象列表%]中教程的百分比}
{%if Tutorials.categories==“pythonbasics”%}

创建日期:{{Tutorials.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 %}
{%block content%}
{{Tutorials.title}}
关于{{Tutorials.datetime}
{{Tutorials.content | linebreaks}}
{%endblock%}

您应该在模板中使用
对象
名称:

{% block content %}
    <h3>{{ object.title }}</h3>

    <h6> on {{ object.datetime }}</h6>

    <div class = "code">
        {{ object.content|linebreaks }}
    </div>
{% endblock %}

再加上@neverwanner的回答

之所以可以使用
object
context\u object\u name
是因为继承了
DetailView

DetailView
中,它有
get\u 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
它将返回模型对象,您也可以重写此方法

DetailView
中的
get()
方法中

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()
,这样您就可以在
DetailView
中使用
self.object

最后,您可以在模板中使用
object
,因为
get\u context\u data()

DetailView
基本上是将“object”添加到上下文中,这样您就可以使用它了

def get_context_data(self, **kwargs):
    """Insert the single object into the context dict."""
    context = {}
    if self.object:
        context['object'] = self.object
        context_object_name = self.get_context_object_name(self.object)
        if context_object_name:
            context[context_object_name] = self.object
    context.update(kwargs)
    return super().get_context_data(**context)
CBV确实有一些学习曲线,但当您看到django源代码并阅读文档时,很容易理解


+我强烈推荐-您可以看到CBV继承了哪个视图和mixin,以及它的方法

您可以共享任何错误吗?日志中没有任何内容,只是不会显示任何内容。没有错误@mehrdad pedramfarIt成功了但为什么?我发誓我写的是模型名而不是对象,运行的是相同的代码。谢谢你,顺便说一句@neverwalkaloner@Sahil可能您使用了
context\u object\u name='Tutorials'
参数。如果将此参数传递给DetailView
Tutorials
变量,则该变量也将被对象辅助。
def get_context_data(self, **kwargs):
    """Insert the single object into the context dict."""
    context = {}
    if self.object:
        context['object'] = self.object
        context_object_name = self.get_context_object_name(self.object)
        if context_object_name:
            context[context_object_name] = self.object
    context.update(kwargs)
    return super().get_context_data(**context)