如何在django / mezzanine模板中显示上传的django ImageField?

时间:2015-03-11 23:24:34

标签: django apache django-templates mezzanine imagefield

我不知道这里有什么线索。我已经设置了一个带有ImageField的表单,通过前端上传用户图片,上传工作正常,但我无法找到一种方法来检索图片网址并将其显示在模板中。我确实运行了python manage.py collectstatics。模板文件和CSS加载正常,但没有任何上传的图片。 非常欢迎任何帮助!

models.py

class Profil(models.Model):
    def content_file_name(instance, filename):
        return '/'.join(['pics', instance.user.username, filename])
    user_pic = models.ImageField(upload_to=content_file_name, blank=True, verbose_name='Foto')

template.html

<form class="mezzanine-form" action="" method="post" enctype="multipart/form-data">
    <fieldset>
    <legend>Edit Profile</legend>
<img src="{{MEDIA_URL}}pics/{{user.username}}/{{WHAT_SHOULD_BE_HERE?}}">
    {% fields_for profile_form %}
    {% csrf_token %}
    <div class="form-actions">
        <input class="btn btn-primary btn-lg pull-right" type="submit" value="Save">
    </div>
    </fieldset>
</form>

settings.py

PROJECT_ROOT = "/path/to/project/"
PROJECT_DIRNAME = PROJECT_ROOT.split(os.sep)[-1]
CACHE_MIDDLEWARE_KEY_PREFIX = PROJECT_DIRNAME
STATIC_URL = "/static/"
STATIC_ROOT = os.path.join(PROJECT_ROOT, STATIC_URL.strip("/"))
STATICFILES_DIRS = [
    os.path.join(PROJECT_ROOT, "static"),
    "/path/to/project/static/",
]
MEDIA_URL = STATIC_URL + "media/"
MEDIA_ROOT = os.path.join(PROJECT_ROOT, *MEDIA_URL.strip("/").split("/"))
ROOT_URLCONF = "%s.urls" % PROJECT_DIRNAME
TEMPLATE_DIRS = (os.path.join(PROJECT_ROOT, "templates"),)

的httpd.conf

Alias /media/ /path/to/project/static/media/
Alias /static/ /path/to/project/static/

<Directory /path/to/project/static/>
Order allow,deny
Allow from all
</Directory>

<Directory /path/to/project/static/media>
Order allow,deny
Allow from all
</Directory>

1 个答案:

答案 0 :(得分:0)

您可以使用.url()的{​​{1}}方法。我假设您的ImageField模型中有ForeignKeyUser,因此模板代码应为:

Profil