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

How to display uploaded django ImageField in django/mezzanine template?

我在这里一无所知。我已经使用 ImageField 设置了一个表单来通过前端上传用户图片并且上传工作正常,但我找不到检索图片 url 并将其显示在模板中的方法。我做了 运行 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>

可以使用ImageField.url()方法。我假设你的 Profil 模型中有一个 ForeignKeyUser,所以模板代码应该是:

<img src="{{ user.profil.user_pic.url }}">