0

我正在尝试创建一个 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'),
)
4

2 回答 2

0

您还需要为获取请求创建表单。

将您的视图更新为

def detail(request, page_id):
    if request.method == 'POST':
    ....
    else:
        p = Page.objects.get(pk=page_id)
        form = PageForm(instance=p)
    ....

此外,当表单无效时不要创建新表单,因为它不会显示任何错误。

于 2013-01-26T07:36:44.510 回答
0

谢谢凯茜和罗汉!这对我有用:

视图.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))

网址.py:

urlpatterns = patterns('',
    url(r'^page/(?P<page_id>\d+)/$', 'pages.views.detail'),
)
于 2013-01-26T16:34:34.630 回答