保存后检索ModelForm pk

时间:2015-03-31 22:30:28

标签: django django-models django-forms

模特:

class Users(models.Model):  
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    email = models.CharField(max_length=100)

class Event(models.Model):
    event_admin = models.ForeignKey(Users)
    event_name = models.CharField(max_length=50)
    event_location = models.CharField(max_length=50)
    event_date = models.DateField()
    event_time = models.TimeField()
    event_notes = models.CharField(max_length=200)

查看:

 if request.method == 'POST':        
    EventForm = CreateEventForm(request.POST,prefix = "EventForm")
    UserForm = UserInfoForm(request.POST, prefix = "UserForm")        
    if EventForm.is_valid() and UserForm.is_valid():            

        UserForm.save()

        #Problem is here
        retrieveID= UserForm.id

        Event1 = EventForm.save(commit=False)            
        Event1.event_admin= retrieveID
        Event1.save()

我有2个模型发布到1个表单。在第一个保存之后,我试图将其id / pk保存为第二个表单中的外键字段。但是,我收到属性不存在的错误。

1 个答案:

答案 0 :(得分:3)

UserForm.save()返回一个新创建的对象,得到它:

obj = UserForm.save()