0

The website I was working on involves uploading of some files and downloading them. But I have to display the path where an uploaded file is stored. So a model FileField named 'bulk_add' is added in models.py to store filepath like this:

bulk_add = models.FileField(upload_to=assignment_bulk_upload_path, null=True)

So when user has uploaded a file, I have to display the path where the file is stored in my website like this: Screen shot

But as FileField by default will allow max_length = 100, whenever the user uploads a file with very long name, the entire length of filepath crosses the default maxlength(since filepath involves filename) and error page is shown.

So I want to write a python function to get the number of characters in filepath when a file is uploaded and display error "File name is long" when the filepath length crossses 100. So how to get no of characters in filepath in the FileFIeld?

Is there a function like length() so that I'll get the no. of chars in filepath when I do bulk_add.length()?

Light Yagami
  • 961
  • 1
  • 9
  • 29
  • Well then this is nothing you should handle at the models layer, but on the *forms*/*views* layer. – Willem Van Onsem Jun 13 '18 at 09:17
  • Yes on forms, I wanna write a function which will return error message if it exceeds length 100 else return empty message. But I don't know how to do it. – Light Yagami Jun 13 '18 at 09:22
  • Simple increase length of file field with `max_length=250`, This should work https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.FileField.storage – Anup Yadav Jun 13 '18 at 09:36
  • @AnupYadav: that's not a good idea, since most operating systems place restrictions on the size of the filepath (typically ~250 chars). – Willem Van Onsem Jun 13 '18 at 09:38
  • @WillemVanOnsem Then increase upto 250. – Anup Yadav Jun 13 '18 at 09:38
  • @AnupYadav: well since it is a relative path, we do not now how long the prefix is. Regardless of that, it is simply horrible design, since it makes unverified assumptions (regarding the OS). Especially in the early days, this also had a lot of security risks. – Willem Van Onsem Jun 13 '18 at 09:41
  • 1
    @AnupYadav max_length=250 is not giving error when it is more than 250. – Light Yagami Jun 13 '18 at 10:43
  • So you expect to get that error or what? – Anup Yadav Jun 13 '18 at 11:57

0 Answers0