8
def generate_uuid_file_name(self, filename):
    self.original_filename = filename
    extension = filename.rsplit('.', 1)[1]
    newfilename = uuid.uuid4().__str__() + '.' + extension
    return self.directory() + newfilename

class FileUpload(models.Model):
    original_filename  = models.CharField(max_length=128)
    fileobj            = models.FileField(upload_to=generate_uuid_file_name)

On upload,

{"errors": {"original_filename": ["This field is required."]}, "success": false}

Adding blank=True, null=True to the FileUpload.original_filename allows the upload to succeed but does not save the original file name. On Django 1.5. According to this post, this should work.

halfer
  • 19,824
  • 17
  • 99
  • 186
Wade Williams
  • 3,943
  • 1
  • 26
  • 35

1 Answers1

8

Do that in the view (after null=True, blank=True are again part of your model):

file_object = UploadFileForm.save(commit=False)
file_object.original_filename = request.FILES['file'].name
file_object.save()

Mind that you will need to change the above code accordingly with your context etc

Samuele Mattiuzzo
  • 10,760
  • 5
  • 39
  • 63
  • So, that totally worked. However, I'm still a little confused as to why the self.original_filename above didn't ?? My understanding is that it's passed by reference so the original code should have worked ? – Wade Williams Jun 28 '13 at 03:50
  • If the `original_filename` field was before the `fileobj` field, it would work. – kb1000 Jun 02 '17 at 11:55
  • 3
    Man, I love django. – Joel Hernandez Sep 12 '17 at 08:14
  • If your model has a many-to-many relationship with another model you should use `file_object.save_m2m()` in the end of the suggested code. – pgmank Apr 16 '18 at 21:51