0

I am using django 1.4 and using django model's filefield to upload some document via modelform. I am having following issues:

When I submit form it says:

Data truncated for column 'file_name' at row 1

Following is my model for this:

class App(models.Model):
    user_name=models.CharField(max_length=50)
    email=models.CharField(max_length=50)
    status=models.CharField(max_length=10,choices=APPLICATIONSTATUSCHOICE)
    archived=models.BooleanField()
    mark_spam=models.BooleanField()
    date=models.DateField()
    file_name=models.FileField(upload_to=PATH+"/")
    def getPath(self):
        return PATH
    def __unicode__(self):
        return self.user_name
    def send_email(self):
        pass

Here is the code for model form:

class AppForm(ModelForm):
    class Meta:
     model=App
         exclude=('status','archived','mark_spam')

email=forms.EmailField()

    def save(self,commit=True):
         app=super(AppForm,self).save(commit=False)
     app.status='sent'
         app.save()

Also it is storing file with its original name,can I have it with something unique name as I am from PHP background and in PHP I normally save it like <mysql auto id>.<filextension>, so how can I do it in django. My first impression was that all this will be automatically done via django while it just save it with name of its own choice but I need to save names into db also so want to name them according to my choice. How can it be done and what is problem in my code that is giving above mentioned error?

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
Hafiz
  • 4,187
  • 12
  • 58
  • 111

1 Answers1

2

How long is the file_name you are trying to store?

By default, FileField instances are created as varchar(100) columns in your database. As with other fields, you can change the maximum length using the max_length argument. That might be resulting the data truncation error.

Also you can rename your file whatever you want. the upload_to can be a callable that takes the instance and the name of the uploaded file as input and then you can specify the exact name and path you want to store.

Eg.

def get_file_name(instance, filename):
    return '/'.join(['blah', instance.user.username, filename])

...
    file_name=models.FileField(upload_to=get_file_name)
...
Pratik Mandrekar
  • 9,362
  • 4
  • 45
  • 65
  • In my db it is varchar(50) , also I have just seen that it is insesrting full path to my file not just name, this don't seem correct behaviour, is it? Also for uploading file according to app_id then do I need to insert record first separately? to get its auto incremented id or django have something for it ? – Hafiz Oct 07 '12 at 09:55
  • 1
    What db are you using, try specifying a `max_length=200` and recreate the tables or migrate if using south. The file path is usually relative to the 'MEDIA_PATH' specified in the `settings.py` – Pratik Mandrekar Oct 07 '12 at 10:08