0

模型.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)

表格.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.Example 中编写代码以使用两个表来做同样的事情我没有看到。

谢谢

4

1 回答 1

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>
于 2013-03-14T08:30:24.157 回答