我是 python 和 Django 的新手,我已经开始了一个示例项目“博客”。
目前博客文章是手动添加到数据库中的,但我想在前端通过向用户提供表单来完成。我创建了我的model.py
和views.py
文件,但我无法在前端看到这些字段。我在下面复制了我的所有代码:
模型.py:
class posts(models.Model):
author = models.CharField(max_length = 30)
title = models.CharField(max_length = 100)
bodytext = models.TextField()
timestamp = models.DateTimeField()
class postForm(ModelForm):
class Meta:
model = posts
视图.py:
def home(request):
content = posts.objects.all()[:5]
return render_to_response('index.html',{'posts' : content})
def save_blog(request):
form = postForm
if request.POST:
form = postForm(request.POST)
if form.is_valid():
form.save
return render_to_response('index.html',{'form' : form},context_instance=RequestContext(request))
网址.py:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns =
patterns('',
url(r'^$', 'blog.views.home', name='home'),
url(r'^admin/', include(admin.site.urls))
)
索引.html:
<body>
<div class="container">
<h1>Welcome To</h1>
<hr />
{% for post in posts %}
<div class="posts">
<h2>{{ post.title }}</h2>
<h3>Posted on {{ post.timestamp }} by {{ post.author }}</h3>
<p>{{ post.bodytext }}</p>
</div>
<hr />
{% endfor %}
</div>
<div class="forms">
<form action="." method="post" name="posts" id="posts">{% csrf_token %}
<table>
<tr><td>{{form.author.label}}</td><td>{{form.author}}</td></tr>
<tr><td>{{form.title.label}}</td><td>{{form.title}}</td></tr>
<tr><td>{{form.bodytext.label}}</td><td>{{form.bodytext}}</td></tr>
<tr><td></td><td><input type="button" name="btnSave" id="bntSave" value="Submit" class = "default2"/></td>
</table>
</form>
</div>
</body>
settings.MIDDLEWARE_CLASSES:
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
如果我遗漏任何东西,请告诉我。也让我知道如何在不使用 Django 模型表单的情况下实现这一点。
谢谢