编辑和更新数据库中已存在的数据

时间:2013-03-11 09:35:41

标签: django-models django-forms django-templates

任何人都可以指导我如何编辑和保存数据库中的现有数据

def editbook(request,book_id):

    if request.POST:
    book = Book.objects.get(pk=book_id)
        form = BookForm(request.POST,instance = book)
        if form.is_valid():
            form.save()
            return redirect('/index/')
    else:
        book = Book.objects.get(pk = book_id)       
        form = BookForm(instance = book)
        return render_to_response('editbook.html',{ 'form':form }, context_instance=RequestContext(request))

模板是

<html>
<head>
<title>{{ page_title }}</title>
</head>
<body>   
<div align="center">
<form action="/editbook/{{ form.book_id }}/" method="POST" class="BookForm"> {% csrf_token %}
<table>
  <tr>
    <td align="right">Book Name : </td> 
    <td align="left">{{ form.book_name }}
</tr>
  <tr>
    <td align="right">Author Name :</td> 
    <td align="left">{{ form.author_name }}</td>
</tr>
<tr>
  <tr><td align="right">Publisher Name : </td>
  <td align="left"> {{ form.publisher_name }}</td>  
</tr>
</table>
<input type="submit" value="Save">
</form>
</div>
</body>
</html>

当我按下保存按钮时,数据未保存到数据库中。它显示错误,因为找不到页面(404)。

urls.py是

from django.conf.urls import patterns, include, url
from DemoApp.views import index,addbook,editbook, book_detail,deletebook
from django.contrib import admin

admin.autodiscover()

urlpatterns = patterns('',
    url('^$', index),
    url('^index/$', index),
    url('^addbook/$', addbook),
    url('^book_detail/$', book_detail, 'book_summary'),
    url('^editbook/(?P<book_id>\d+)/$', editbook) ,
    url('^deletebook/(?P<book_id>\d+)/$',deletebook) ,


    #url(r'^admin/', include(admin.site.urls)),


)

1 个答案:

答案 0 :(得分:1)

1)你给出的模板是错误的。

2)请参阅index.html以调用表单