Django FileField url不是相对的 [英] Django FileField url not relative

查看:531
本文介绍了Django FileField url不是相对的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些类似的东西:

  MEDIA_ROOT ='/ home / httpd / foo / media /'
MEDIA_URL ='http://www.example.org/media/'

(...)

  file = models.FileField(upload_to ='test')

当我在管理页面中创建一个对象时,Django会在DB中存储完整的文件路径,如:/ home / httpd / foo / media / test / myfile.pdf。这与文档中所说的相反


将存储在
数据库中的所有文件都是文件路径
(相对于MEDIA_ROOT)。


当我在模板中使用file.url时,我会得到以下内容:


http://www.example.org/home/httpd/foo/media/test/myfile.pdf


而不是我想要的:


http://www.example.org/media/test/myfile.pdf


我做错了什么?

解决方案

我刚刚在我的一个项目中做了一个示例FileField它似乎像你所期待的那样工作。这里有几件事要尝试。



尝试进行如下设置。我知道他们说这是不好的结束你的MEDIA_URL与/但这是我如何做,我喜欢它更好。只要您在模板中使用MEDIA_URL,只需使用斜杠即可记住:href ={{MEDIA_URL}} / path / to / file

  MEDIA_ROOT ='/ home / httpd / foo / media'
MEDIA_URL ='/ media'

如果没有什么帮助,创建一个新的简化模型,FileField没有任何定制,看看你是否仍然遇到同样的问题。


I have something like:

MEDIA_ROOT = '/home/httpd/foo/media/'
MEDIA_URL = 'http://www.example.org/media/'

(...)

file = models.FileField(upload_to='test') 

When I create an object with that field in the admin page Django stores in the DB the full file path, like: "/home/httpd/foo/media/test/myfile.pdf". This is contrary to what says in the docs.

All that will be stored in your database is a path to the file (relative to MEDIA_ROOT).

When I use the file.url in a template I get something like:

http://www.example.org/home/httpd/foo/media/test/myfile.pdf

instead of what I would like:

http://www.example.org/media/test/myfile.pdf

What am I doing wrong?

解决方案

I just did a sample FileField in one of my projects and it seemed to work as you are expecting. Here are a couple things to try.

Try making your settings like the following. I know they say it is bad to not end your MEDIA_URL with a / but this is how I do it and I like it better. You just have to remember whenever you use MEDIA_URL in a template to follow it with a slash: href="{{ MEDIA_URL }}/path/to/file"

MEDIA_ROOT = '/home/httpd/foo/media'
MEDIA_URL = '/media'

If that doesn't help anything, create a new simplified model with a FileField nothing customized and see if you are still getting the same problem.

这篇关于Django FileField url不是相对的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆