2011-09-15 72 views

回答

22

當您保存模型窗體時,它將返回保存的模型實例。因此,所有你需要做的就是把它分配給一個變量:

f = MyModelForm(request.POST) 
if f.is_valid(): 
    m = f.save() 

,除非你要處理更復雜的數據,您不需要更動commit=False或任何東西。

4

啊我剛剛發現這個!

# Create a form instance with POST data. 
>>> f = AuthorForm(request.POST) 

# Create, but don't save the new author instance. 
>>> new_author = f.save(commit=False) 

# Modify the author in some way. 
>>> new_author.some_field = 'some_value' 

# Save the new instance. 
>>> new_author.save() 

# Now, save the many-to-many data for the form. 
>>> f.save_m2m() 
9

如果你知道,該模型被保存(以便正確的實例存在),你也可以這樣做:

model = form.instance