4👍
You can parse the file prior to saving, and generally I like to do this in the model clean()
method:
def clean(self):
file_contents = self.Gpxfile.read()
...do stuff
If the file doesn’t meet your validation criteria, you can raise a ValidationError
in clean which will propagate back to the calling view so you can report the form errors back to the user.
If you really need to save the file first and then do something, you could use a post_save
signal
def some_function_not_in_the_model(sender, **kwargs):
obj = kwargs['instance']
...do stuff with the object
# connect function to post_save
post_save.connect(some_function_not_in_the_model, sender=Track)
Finally, one note about large files is that they may end up as temporary files on the server (in Linux /var/tmp or similar…this can be set in settings.py). It may be a good idea to check this within the clean()
method when trying to access the file, something like:
# check if file is temporary
if hasattr(self.Gpxfile.file, 'temporary_file_path'):
try:
file_path = self.Gpxfile.file.temporary_file_path(),
except:
raise ValidationError(
"Something bad happened"
)
else:
contents = self.Gpxfile.read()
Oh, and finally finally, be careful about closing the temporary file. Back when I started using Django’s FileField and learned how the temporary file worked, I thought I’d be the good programmer and close the file after I was done using it. This causes problems as Django will do this internally. Likewise, if you open the temporary file and raise a ValidationError, you will likely want to remove (unlink) the temp file to prevent them from accumulating in the temp directory.
Hope this helps!