使用django编辑和更新数据库中的行

时间:2013-03-14 07:07:15

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

models.py

class Author(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=40)
    email = models.EmailField()
    age = models.IntegerField()

    def __unicode__(self):
        return "{0} {1} {2} {3} {4}".format(
            self, self.first_name, self.last_name, self.email, self.age)

class Book(models.Model):
    book_name=models.CharField(max_length=30)
    publisher_name=models.CharField(max_length=40)
    author=models.ForeignKey(Author)

    def __unicode__(self):
        return "{0} {1} {2}".format(
            self.pk, self.book_name, self.publisher_name)

forms.py

class AuthorForm(ModelForm):
    class Meta:
        model = Author     

BookFormset = inlineformset_factory(Author, Book, 
    fields=('book_name', 'publisher_name'), extra=1, 
    can_delete=False) 

urls.py是

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)),


)

我需要执行编辑并更新数据库中的行,我是通过使用单个表来完成的。但是使用两个表有一些混淆如何使用该特定id获取第二个表。我在此使用表单。可以帮助我在这里写了一些在views.py中的代码。例如,使用两个表做同样的事情是我见过的地方。

谢谢

1 个答案:

答案 0 :(得分:1)

def update_book(request, book_id):
    author = get_object_or_404(Author, pk=author_id)

    form = AuthorForm(instance=author)
    book_formset = BookFormset(instance=author)

    if request.method == 'POST':
        form = AuthorForm(request.POST, instance=author)
        if form.is_valid():
            author = form.save(commit=False)
            book_formset = BookFormset(request.POST, instance=author)
            if book_formset.is_valid():
                author.save()
                book_formset.save()
                return redirect('/index/')

    return render_to_response('updatebook.html',{
        'form': form, 'formset': book_formset
    },context_instance=RequestContext(request)) 


<div align="center">
    <tr>
        <form method="POST"> 
            {% csrf_token %} 
            <h5>Author:</h5>
            {{ form.as_p }}

            <h5>Book:</h5>
            {{ formset.as_p }}
            <input type="submit" value="submit">
        </form>
    </tr>
</div>