如何通过在Django中加载字符串来调用函数



我是Django的新手,我正在测试,如果我有posts.html模板,我想在页面上以摘要形式加载所有帖子,但一侧会加载偶数id的帖子,另一侧会加载奇数id的帖子。

我在views.py中做了一个函数,想加载posts.html中的所有帖子。

def posted(request):
posts = Album.objects.all()
for post in posts:
if post % 2 == 0:
return render(request, """<div class="container marketing  ">
<div class="row mb-2 " >
<div class="col-md-6">
<div class="row g-0 border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md-250 position-relative">
<div class="col p-4 d-flex flex-column position-static">
<strong class="d-inline-block mb-2 text-primary">{{ post.title }}</strong>
<h3 class="mb-0">{{ post.author.get_full_name }}</h3>
<div class="mb-1 text-muted">{{ post.created_at|date:'d, M Y'}}</div>
<p class="card-text mb-auto">{{ post.summary|safe }}</p>
<a href="/post/{{ post.pk }}" class="stretched-link">Continue reading</a>
</div>
<div class="col-auto d-none d-lg-block">
<img class="bd-placeholder-img" width="200" height="250" src="{{post.image.url}}" role="img" aria-label="Placeholder: Thumbnail" preserveAspectRatio="xMidYMid slice" focusable="false"><title>Placeholder</title><rect width="100%" height="100%" fill="#55595c"/></img>
</div>
</div>
</div>""",)
return render(request, """<div class="col-md-6">
<div class="row g-0 border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md-250 position-relative">
<div class="col p-4 d-flex flex-column position-static">
<strong class="d-inline-block mb-2 text-success">Design</strong>
<h3 class="mb-0">Post title</h3>
<div class="mb-1 text-muted">Nov 11</div>
<p class="mb-auto">This is a wider card with supporting text below as a natural lead-in to additional content.</p>
<a href="#" class="stretched-link">Continue reading</a>
</div>
<div class="col-auto d-none d-lg-block">
<img class="bd-placeholder-img" width="200" height="250" src="{% static "images/pexels-pixabay-159358.jpg"%}" role="img" aria-label="Placeholder: Thumbnail" preserveAspectRatio="xMidYMid slice" focusable="false"><title>Placeholder</title><rect width="100%" height="100%" fill="#55595c"/></img>
</div>
</div>
</div>
</div>""")

您似乎不知道return是如何工作的。它一次完成函数,所以在您的代码中,您可以在第一个post之后完成函数。

如果你想在页面上发布所有帖子,那么你必须将它们全部发送到模板中,并在此模板中使用特殊的{% for %}{% if/else %}

功能

def posted(request):
posts = Album.objects.all()
return render(request, """template""", posts)

和模板

"""
{% for post in posts %}
{% if forloop.counter % 2 == 0 %}:
<!-- ... html for even post ... -->
{% else %}
<!-- ... html for odd post ... -->
{% enif %}
{% endfor %}
"""

我认为我们必须对您的代码进行重大改造。首先,使用Django的"render"函数会让你的生活轻松很多。你首先需要做的是在settings.py:中设置你的base_dir

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

现在在settings.py中设置模板_dir:

TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates')
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'django.template.context_processors.media',
],
},
},
]

既然已经完成了,在项目的基本目录中创建一个名为"templates"的文件夹。现在,在"templates"文件夹中创建一个名为"view.html"的文件。在新的html中粘贴以下css:

<style>
/* Create two equal columns that floats next to each other */
.column {
float: left;
width: 50%;
padding: 10px;
}
/* Clear floats after the columns */
.row:after {
content: "";
display: table;
clear: both;
}
</style>

现在,将视图中的所有html复制到html文件中。要制作2列,请将每列的html放在以下位置:

<div class="row">
<div class="column"
</div>
</div>

无论在其中放入什么html,都将成为浏览器窗口宽度的50%的列。但是如何将信息发送到模板?如下修改您的视图:从django.shortcuts导入渲染

def posted(request):
posts = Album.objects.all()
return render(request, 'view.html', {'posts': posts})

请注意,我们不是在视图中使用for循环,而是将其移动到模板中。但是你如何分配职位呢?在html中,您希望使用{%for%}、{%ifequal%}和{%ifnotequal%}标记。因此,在id为偶数的项目栏中,您将输入:

{% for post in posts %}
{% ifequal post.id is divisible by(2) True %}
<div class="container marketing  ">
<div class="row mb-2 " >
<div class="col-md-6">
<div class="row g-0 border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md-250 position-relative">
<div class="col p-4 d-flex flex-column position-static">
<strong class="d-inline-block mb-2 text-primary">{{ post.title }}</strong>
<h3 class="mb-0">{{ post.author.get_full_name }}</h3>
<div class="mb-1 text-muted">{{ post.created_at|date:'d, M Y'}}</div>
<p class="card-text mb-auto">{{ post.summary|safe }}</p>
<a href="/post/{{ post.pk }}" class="stretched-link">Continue reading</a>
</div>
<div class="col-auto d-none d-lg-block">
<img class="bd-placeholder-img" width="200" height="250" src="{{post.image.url}}" role="img" aria-label="Placeholder: Thumbnail" preserveAspectRatio="xMidYMid slice" focusable="false"><title>Placeholder</title><rect width="100%" height="100%" fill="#55595c"/></img>
</div>
</div>
</div>
{% endfor %}
{% endifequal %}

对于id为奇数的项目:

{% for post in posts %}
{% ifnotequal post.id is divisible by(2) True %}
<div class="container marketing  ">
<div class="row mb-2 " >
<div class="col-md-6">
<div class="row g-0 border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md-250 position-relative">
<div class="col p-4 d-flex flex-column position-static">
<strong class="d-inline-block mb-2 text-primary">{{ post.title }}</strong>
<h3 class="mb-0">{{ post.author.get_full_name }}</h3>
<div class="mb-1 text-muted">{{ post.created_at|date:'d, M Y'}}</div>
<p class="card-text mb-auto">{{ post.summary|safe }}</p>
<a href="/post/{{ post.pk }}" class="stretched-link">Continue reading</a>
</div>
<div class="col-auto d-none d-lg-block">
<img class="bd-placeholder-img" width="200" height="250" src="{{post.image.url}}" role="img" aria-label="Placeholder: Thumbnail" preserveAspectRatio="xMidYMid slice" focusable="false"><title>Placeholder</title><rect width="100%" height="100%" fill="#55595c"/></img>
</div>
</div>
</div>
{% endfor %}
{% endifnotequal %}

css和Django的完美模板系统的结合应该可以解决您的问题,并简化代码。此外,不要忘记在视图中导入您的模型!另外,我建议你从图书馆里找一本关于Django的好书,通读整本书;它将帮助您了解如何最大化Django的功能。另外,w3schools.com是css的一个很好的资源,simpleisbetterthancomplex.com是Django的greta。否则,祝Django好运(顺便说一句,我4个月前才开始(,如果有什么不起作用,就回应!

最新更新