Pergunta

I'm in the middle of a very strange issue here.

I have a FileField with a default value in a model declared as follow:

class MyModel(models.Model):
    name = models.CharField(max_length=32)
    audio_file = models.FileField(upload_to='user_menus/', default='%suser_menus/default.mp3' % settings.MEDIA_ROOT, blank=True, null=False)

Now, when I do the following

>>> a = MyModel(name='Foo')
>>> a.save()
>>> a.audio_file.path
'/full/path/to/file'
>>> a.audio_file.url
'/full/path/to/file'   # again

I have my MEDIA_ROOT and MEDIA_URL configured as follows

MEDIA_ROOT = os.path.join(os.path.dirname(__file__), 'static/')
MEDIA_URL = '/media/'

Am i missing something? any advice?

Thank you in advance.

Foi útil?

Solução

You need to specify in the default value of the field the actual value (string) you want to save in the database, not the full path. That's why the .url is showing up that way. For your case should be like this:

audio_file = models.FileField(upload_to='user_menus/', default='%suser_menus/default.mp3' % settings.MEDIA_URL, blank=True, null=False)

Notice that I just think you'll having this problem when the default is inserted in the database.

Hope this helps!

Outras dicas

There are a couple of things I don't think you need, which may or may not be causing the problem. I have the following code working perfectly in production (Django 1.5). models.py:

...
    decision_file = models.FileField(
        upload_to = "guidance",
        blank = True,
        help_text = "20MB maximum file size."
    )
...

And in my base settings.py:

MEDIA_ROOT = os.path.join(os.path.dirname(__file__), '../../media')

MEDIA_URL = '/media/'

STATIC_ROOT = os.path.join(os.path.dirname(__file__), '../../static/')

STATIC_URL = '/static/'

Notice I'm defining separate paths and urls for static and media files. I don't think you should include the format string with % settings.MEDIA_ROOT in your default (see Paulo Bu's answer) or use the trailing slash in the upload_to parameter.

In summary

  1. check the upload folder exists;
  2. set separate static and media paths and urls;
  3. remove the format string from your defaul; and
  4. remove the trailing slash from the upload_to parameter

and you should have working code.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top