目标/tl;博士当您提交论坛并使用文本字段中的内容创建新的帖子对象时,我想从views.py 中调用我添加的方法。
我是 django 的新手,我查看了其他堆栈帖子,但大多数这些错误似乎是针对 cookie 或用户的。正如大多数人所建议的那样,我还查看了 python 文档,但我还没有看到所有的部分,我不确定如何从论坛获取文本字段。正确的代码和/或我做错了什么以及如何做的解释将不胜感激。
模型.py
from django.db import models
class Post(models.Model):
text = models.TextField(max_length=250)
time = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return self.text
视图.py
from django.http import Http404, HttpResponse
from django.shortcuts import render_to_response, redirect
from blog.models import Post
from django.core.context_processors import csrf
def home(request):
try:
p = Post.objects.all()
except Post.DoesNotExist:
raise Http404
return render_to_response('index.html',
{'post':p})
def post(request, uID):
try:
p = Post.objects.get(pk=uID)
except:
raise Http404
return render_to_response('post.html',
{'post':p})
def delete(request, uID):
try:
p = Post.objects.get(pk=uID).delete()
except:
raise Http404
return render_to_response('delete.html',
{'post':p})
def new(request):
context = {}
context.update(csrf(request))
return render_to_response('new.html', context)
def added(request):
if request.method == 'POST':
context = {}
context.update(csrf(request))
p = Post.objects.create(text=request.text)
p.save()
return render_to_response("index.html", context)
else:
raise Http404
网址.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'^(?P<uID>\d+)/$', 'blog.views.post', name='Post Id'),
url(r'^(?P<uID>\d+)/delete/$', 'blog.views.delete', name='del'),
url(r'^new/$', 'blog.views.new'),
url(r'^created/$', 'blog.views.added'),
# url(r'^myApp/', include('myApp.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
)
新的.html
<html>
<body>
<h2> Create a new Post </h2>
<form method="post" action="/created/">
{% csrf_token %}
Body: <input type="textarea" name="text">
<input type="submit" value="Submit">
</form>
</body>
</html>