# 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)
class UserForm(forms.ModelForm):
...
def save(self):
# Sets username to email before saving
user = super(UserForm, self).save(commit=False)
user.username = user.email
user.save()
return user
如果您没有使用 commit=False将用户名设置为电子邮件地址,那么您要么必须修改用户模型的 save 方法,要么必须将用户对象保存两次(这将复制一个昂贵的数据库操作)
form = AddAttachmentForm(request.POST, request.FILES)
if form.is_valid():
attachment = form.save(commit=False)
attachment.user = student
attachment.attacher = self.request.user
attachment.date_attached = timezone.now()
attachment.competency = competency
attachment.filename = request.FILES['attachment'].name
if attachment.filename.lower().endswith(('.png','jpg','jpeg','.ai','.bmp','.gif','.ico','.psd','.svg','.tiff','.tif')):
attachment.file_type = "image"
if attachment.filename.lower().endswith(('.mp4','.mov','.3g2','.avi','.flv','.h264','.m4v','.mpg','.mpeg','.wmv')):
attachment.file_type = "video"
if attachment.filename.lower().endswith(('.aif','.cda','.mid','.midi','.mp3','.mpa','.ogg','.wav','.wma','.wpl')):
attachment.file_type = "audio"
if attachment.filename.lower().endswith(('.csv','.dif','.ods','.xls','.tsv','.dat','.db','.xml','.xlsx','.xlr')):
attachment.file_type = "spreasheet"
if attachment.filename.lower().endswith(('.doc','.pdf','.rtf','.txt')):
attachment.file_type = "text"
attachment.save()
here is my example of using save(commit=False). I wanted to check what type of file a user uploaded before saving it to the database. I also wanted to get the date it was attached since that field was not in the form.
In simple words, here we update the form object and let them know that don't save the values in the database right now, we might change some input with instance and then use .save() to save all values in the database.
# Create a form instance with POST data.
>>> form_data = AnswerForm(request.POST)
# Create, but don't save the new answer instance.
>>> Answer = form_data.save(commit=False)