0

在我看来.py

def addinfo(request):
    profile_form = ProfileForm()
    book_form = BookForm(instance=Profile())

    if request.POST:

        profile_form=ProfileForm(request.POST)

        if profile_form.is_valid():
            profile=Profile_form.save()

            book_form=BookForm(request.POST,instance=profile)

            if book_form.is_valid():
                book_form.save()

模型.py 是

class Profile(models.Model):
    profile_id = models.AutoField(primary_key=True)
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=40)
    email = models.EmailField()
    age=models.IntegerField()

    class Meta:
    db_table=u'Profile'

    def __unicode__(self):
        return u"%d %s %s %s %d" % (self.pk, self.first_name, self.last_name, self.email,self.age)



class Book(models.Model):
    book_id=models.AutoField(primary_key=True,unique=True)
    book_name=models.CharField(max_length=30)
    publisher_name=models.CharField(max_length=40)
    profile=models.ForeignKey(Author)

    class Meta:
        db_table = u'Book'

    def __unicode__(self):
        return u'%d %s %s' % (self.pk, self.book_name, self.publisher_name)

这是为了将数据保存到两个不同的模型中,我在这个模型中使用表单。一个模型得到更新,另一个表数据没有被插入。不保存页面会刷新。会有什么问题。

4

2 回答 2

2

如果我理解你想要做什么,你应该更换

book_form=BookForm(request.POST,instance=profile)

book = Book(profile_id=profile.id)  
# EDIT shameless copy and paste from Catherine's answer to avoid "profile_id not defined" error
book_form=BookForm(request.POST,instance=book)
if book_form.is_valid():
    book_form.save()


编辑:作为替代方案,您可以更改Book模型以使实例可选:

profile=models.ForeignKey(Author, null=True)

这样,您的视图将变为:

def addinfo(request):
    profile_form = ProfileForm()
    book_form = BookForm()

    if request.POST:
        profile_form=ProfileForm(request.POST)
        if profile_form.is_valid():
            profile=Profile_form.save()
            book_form=BookForm(request.POST)
            if book_form.is_valid():
               book = book_form.save(commit=False)
               book.profile = profile
               book.save()

有关部分的解释,请参见本段中的注释commit=False

于 2013-03-26T10:13:13.987 回答
1
def addinfo(request):
    profile_form = ProfileForm()
    book_form = BookForm(instance=Profile())

    if request.POST:
        profile_form=ProfileForm(request.POST)
        if profile_form.is_valid():
            profile=Profile_form.save()

            book = Book(profile_id=profile.id)
            book_form=BookForm(request.POST,instance=book)
            if book_form.is_valid():
                book_form.save()
于 2013-03-26T10:34:36.100 回答