我正在尝试创建一个更新数据库中记录的ModelForm,但由于某种原因它无法正常工作。结果是空白。我在这里做错了什么?
这是我的forms.py:
class PageForm(ModelForm):
class Meta:
model = Page
这是我的views.py:
def detail(request, page_id):
p = get_object_or_404(Page, pk=id)
if request.method == 'POST':
form = PageForm(request.POST, instance=p)
if form.is_valid():
form.save()
messages.success(request, "Detail updated successfully.")
return HttpResponseRedirect('/thanks/')
return render(request, 'pages/pageform.html', {
'form': PageForm(instance=p),
})
这是我的model.py:
class Page(models.Model):
pub_date = models.DateTimeField('date published')
title = models.CharField(max_length=255)
keywords = models.CharField(max_length=255)
description = models.CharField(max_length=255)
content = models.TextField()
def __unicode__(self):
return self.title
这是我的pageform.html
<form action="/detail/" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
这是我的urls.py
urlpatterns = patterns('',
url(r'^page/(?P<id>\d+)/$', 'detail', name='detail'),
)
答案 0 :(得分:0)
您还需要为 get 请求创建表单。
以
更新您的观点def detail(request, page_id):
if request.method == 'POST':
....
else:
p = Page.objects.get(pk=page_id)
form = PageForm(instance=p)
....
另外,当表单无效时不要创建新表单,因为它不会显示任何错误。
答案 1 :(得分:0)
谢谢Cathy和Rohan!这对我有用:
views.py
def detail(request, page_id):
p = get_object_or_404(Page, pk=page_id)
if request.method == 'POST':
form = PageForm(request.POST or None, instance=p)
if form.is_valid():
form.save()
return HttpResponseRedirect('/thanks/')
else:
form = PageForm(instance=p)
return render_to_response('pages/detail.html', {'page': p, 'form': form}, context_instance=RequestContext(request))
urls.py:
urlpatterns = patterns('',
url(r'^page/(?P<page_id>\d+)/$', 'pages.views.detail'),
)