Django-编辑和更新数据库中的现有数据

时间:2013-03-06 12:41:58

标签: django-models django-forms django-views

models.py是

from django.db import models

    class Book(models.Model):

        book_id=models.AutoField(primary_key=True,unique=True)
        book_name=models.CharField(max_length=30)
        author_name=models.CharField(max_length=30)
        publisher_name=models.CharField(max_length=40)

        class Meta:
            db_table = u'Book'

        def __unicode__(self):
            return "%d %s %s %s" % (self.book_id,self.book_name, self.author_name,self.publisher_name)

forms.py是

from django import forms
from django.forms import ModelForm
from myapp.models import Book


class BookForm(ModelForm):

    class Meta:
        model = Book

        fields=['book_id','book_name','author_name','publisher_name']

我的views.py是

def editbook(request,book_id):

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

我需要编辑和更新数据库中已存在的数据行。我猜他们在views.py中存在一些问题。所以我不确定我的views.py是对的。请检查并告诉我是否有任何问题以及如何继续。

谢谢

1 个答案:

答案 0 :(得分:6)

views.py

 if request.POST:
        book_form = BookForm(request.POST)

    if book_form.is_valid():

        book = Book.objects.get(pk=book_id)
        book_form = BookForm(request.POST, instance = book)
        book_form.save() #cleaned indenting, but would not save unless I added at least 6 characters.
        return redirect('/index/')
    else:
        book = Book.objects.get(pk = book_id)       
        book_form = BookForm(instance=book)

        return render_to_response('editbook.html',{ 'form':book_form }, context_instance=RequestContext(request))