我是django的新手,我在检索我的allpost(我们保存在数据库中)时遇到了麻烦。所有这些都是' allpost'查看我在我的博客'项目。 这是代码 - views.py -
from django.shortcuts import render,redirect
from . models import Post
from django.utils import timezone
from . forms import PostForm
def blog(request):
return render(request,'blog/blogpage.html')
def allpost(request):
post=Post.objects.all()
return render(request, 'blog/allpostpage.html', {'post': Post})
# the posts are not displaying in this template #
def form(request):
if request.method=='POST':
form=PostForm(request.POST)
if form.is_valid():
post=form.save(commit=False)
post.published_date=timezone.now()
post.save()
return redirect('allpost')
else:
form=PostForm()
return render(request,'blog/formpage.html',{'form':form})
urls.py -
from django.conf.urls import url
from . import views
urlpatterns=[
url(r'^$',views.blog,name="blog"),
url(r'^form$',views.form,name="form"),
url(r'^allpost$',views.allpost,name="allpost"),
]
formpage.html -
{% extends 'blog/base.html' %}
<head>
<title>form</title>
</head>
<body>
{% block content %}
<form method="POST" class="post-form">
{% csrf_token %}
{{form.as_p}}
<button type="submit" class="save-btn btn-default">save</button>
</form>
{% endblock %}
</body>
</html>
allpostpage.html -
{% extends 'blog/base.html' %}
{% block content %}
{% for post in post %}
{{post.title}}
{% endfor %}
{% endblock %}
models.py -
from django.db import models
from django.utils import timezone
class Post(models.Model):
title=models.CharField(max_length=200)
content=models.TextField(max_length=500)
published_date=models.DateTimeField(blank=True)
def publish_date(self):
Post.published_date=timezone.now()
Post.save()
def __str__(self):
return self.title
forms.py -
from django import forms
from . models import Post
class PostForm(forms.ModelForm):
class Meta:
model=Post
fields=('title','content')
这些是我的代码。请检查并纠正它。再次,帖子(我们用表单保存)没有显示在&#39; allpostpage&#39; &#39; allpost&#39;中的模板view.Thank You
答案 0 :(得分:3)
在你看来allpost。而不是
return render(request, 'blog/allpostpage.html', {'post': Post})
应该是
return render(request, 'blog/allpostpage.html', {'post': post})
并在你的allpostpage.html中它应该是
{% extends 'blog/base.html' %}
{% block content %}
{% for p in post %}
{{p.title}}
{% endfor %}
{% endblock %}