Question

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?

Was it helpful?

Solution

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)
...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top