【发布时间】:2019-10-05 17:58:31
【问题描述】:
所以,我有一个网站,用户在导航栏上单击“我的博客”,然后向下滚动到 index.html 的那个部分(例如 8000/#blog-section)。我已经在索引页面上有了联系表格。 现在我正在尝试创建博客逻辑以呈现三篇博客文章,但它显示为空白?
我可以为同一个“index.html”页面创建一个单独的视图吗?
Views.py
def index_view(request):
posts = Post.objects.all().order_by('-created_on')
context ={
'posts': posts,
'name': name,
}
form = ContactForm()
if request.method == 'POST':
form = ContactForm(data=request.POST)
if form.is_valid():
# Send email goes here
name = request.POST.get('name')
subject = request.POST.get('subject')
email = request.POST.get('email')
message = request.POST.get('message')
template = get_template('contact_form.txt')
context = {
'subject': subject,
'email' : email,
'message' : message
}
content = template.render(context)
email = EmailMessage(
"Message from Portfolio",
content,
"New inquiry | Portfolio" + '',
['myemail@gmail.com'],
headers = {'Reply to': email}
)
email.send()
return HttpResponseRedirect("/")
return render(request, 'index.html', {'form': form}, context)
Urls.py /blog
from django.urls import path
from . import views
urlpatterns = [
path("", views.blog_index, name="blog_index"),
path("<int:pk>/", views.blog_detail, name="blog_detail"),
path("<category>/", views.blog_category, name="blog_category"),
]
Urls.py /portfolio
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path, include
from .views import index_view, post_view
urlpatterns = [
path('admin/', admin.site.urls),
path('tinymce/', include('tinymce.urls')),
path('', index_view),
path('post/', post_view),
path("#blog-section/", include("blog.urls")),
]
模板
<div class="row d-flex">
{% for post in posts %}
<div class="col-md-4 d-flex ftco-animate">
<div class="blog-entry justify-content-end">
<a href="single.html" class="block-20"
style="background-image: url('{{ post.post_img.url }}');">
</a>
<div class="text mt-3 float-right d-block">
<div class="d-flex align-items-center mb-3 meta">
<p class="mb-0">
<span class="mr-2">{{ post.created_on.date }}|
Categories: </span>
<a href="#" class="mr-2">Admin</a>
<a href="#" class="meta-chat"><span class="icon-chat"></span> 3</a>
</p>
</div>
<h3 class="heading"><a href="{% url 'blog_detail' post.pk%}">{{post.title}}</a></h3>
<p>{{post.overview}}</p>
</div>
</div>
</div>
{% endfor %}
</div>
【问题讨论】:
-
form = ContactForm()缺少括号 -
感谢提醒,我在这里重新格式化时一定被删除了。联系表单有效,但您知道如何让博客文章从同一个索引视图呈现吗?
-
其实可以,但是你必须把所有的东西组合到上下文对象中,然后传递给
render方法。在index.html上,只需将您问题上的模板附加到其中即可。 -
我收到这条消息“UnboundLocalError at / local variable 'context' referenced before assignment”这行:“content = template.render(context)”会干扰上下文吗?或者可能是因为它超出了范围?感谢您的宝贵时间!
-
就是这样!!!它超出了范围,我不得不将它从 if 语句中删除!再次感谢您的宝贵时间!
标签: python django django-views