2
我是django的新手,我在我的'博客'中創建的'allpost'視圖中檢索我的allpost(我們保存在數據庫中)項目。 這裏有codes- views.py-這篇文章沒有顯示哪些保存在django的數據庫中
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')
那是我的代碼。請檢查並糾正它。再次,帖子(我們保存它的形式)不顯示在'allpostpage'模板'allpost'視圖中。謝謝
感謝很多:)。它現在正在工作。 –