Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Increase FileField length

Tags:

django

I'm trying to store a file using a FileField, but the path of the destination of the file is larger than 100 characters. How can I increase the number of allowed characters? I've tried with max_length=255 but didn't work.

Thanks.

Edit: Added model

class File(models.Model):
    Record = models.ForeignKey(Records)
    Title = models.CharField(max_length=255, blank=False)
    File = models.FileField(upload_to='files/Records', blank=False)
    Upload_date = models.DateTimeField(auto_now_add=True)

    def __unicode__(self):
        return self.Title
like image 201
Audoen Avatar asked Oct 26 '14 17:10

Audoen


2 Answers

The Django documentation makes it clear that the FileField takes an optional argument to alter the length of the varchar column used to store the file reference (filename).

Taken from the Django documentation here:

FileField instances are created in your database as varchar columns with a default max length of 100 characters. As with other fields, you can change the maximum length using the max_length argument.

In order to make use of this max_length parameter, you simply add the parameter into the model's field declaration, like so:

class File(models.Model):
    Record = models.ForeignKey(Records)
    Title = models.CharField(max_length=255, blank=False)
    File = models.FileField(upload_to='files/Records', blank=False, max_length=500)
    Upload_date = models.DateTimeField(auto_now_add=True)

def __unicode__(self):
    return self.Title

The max_length of the FileField provided by Django is enforced at the database level. When you make a change to the model definition which must be enforced at the database level, you may find that you must use the syncdb or a migration in order to effect this change in the database. Simply changing the max_length parameter in your model definition will have no effect, unless you then migrate your database to also reflect this change.

In this particular case, the varchar column that represents the reference filename to the file stored in the FileField must be updated to allow filenames of greater length. Please be sure that you have done the necessary database maintenance to ensure that your model's fields are faithfully represented in your database. More information about migrations can be found here.

like image 90
MRHwick Avatar answered Nov 13 '22 16:11

MRHwick


I think your code was cool if you added max_length=255 to FileField, only you forgot to update it in your database (makemigrations -> migrate)

like image 5
ugros Avatar answered Nov 13 '22 16:11

ugros