Django ModelForm: What is save(commit=False) used for?

后端 未结 5 1537
遇见更好的自我
遇见更好的自我 2020-11-28 20:51

Why would I ever use save(commit=False) instead of just creating a form object from the ModelForm subclass and running is_valid() to v

5条回答
  •  生来不讨喜
    2020-11-28 21:06

                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.

提交回复
热议问题