我是python以及Django的新手,並且我已經開始了一個示例項目「blog」。Python和Django博客示例項目
當前博客文章是手動添加到數據庫中,但我想通過向用戶提供表單在前端完成。我創建了我的model.py
和views.py
文件,但我無法在前端看到這些字段。我抄的是我下面的代碼:
models.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
views.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))
url.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))
)
的index.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模型的情況下實現這一點。
感謝
如果你是新用戶,則必須在Python中使用spmething喜歡這名字的類。請參閱http://www.python.org/dev/peps/pep-0008/#class-names – 2013-04-09 08:02:44
[在文檔中]明確給出了在視圖中使用表單的模式(https://docs.djangoproject的.com/EN/1.5 /主題/形式/#使用-A-形式-IN-A視圖)。你爲什麼不使用它? – 2013-04-09 08:43:55