5

我正在尝试显示用户已上传的图像,但无论我尝试什么,我都会收到损坏的链接图标。我已经在 SO 和其他地方搜索并搜索了几天的文档,但无济于事。我是 Django 新手,目前正在开发中,所以我确信我犯了一些其他新手错误,但现在我唯一关心的是在模板中显示上传的图像。

以下是我的代码的相关片段:

设置.py

MEDIA_URL = '/media/media_root/'
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media", "media_root")

网址.py

urlpatterns = [
    url(r'^admin/?', admin.site.urls),
    url(r'^accounts/', include('registration.backends.simple.urls')),
    url(r'^about/?', profiles.views.about, name='about'),
    url(r'^properties/single/?', properties.views.single, name='single_mens'),
    url(r'^properties/married/?', properties.views.married, name='married'),
    url(r'^properties/add/add_photos/?', properties.views.add_photos, name='add_photos'),
    url(r'^properties/add/?', properties.views.add_rental, name='add_rental'),
    url(r'^', profiles.views.home, name='home'),
] 

urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += staticfiles_urlpatterns()

模型.py

class RentalPicModel(models.Model):

    def __unicode__(self):
        return self.image.url

    image = models.ImageField(upload_to="pics/originals/", null=True)
    rental = models.ForeignKey(RentalModel, on_delete=models.CASCADE)

表格.py

class AddPhotosForm(forms.ModelForm):

    class Meta:
        model = RentalPicModel
        fields = ['image', 'rental']

    def clean_image(self):
        return self.cleaned_data['image']

    def clean_rental(self):
        return self.cleaned_data['rental']

视图.py

def add_photos(request):

    form = AddPhotosForm
    current_rental = None
    current_photos = []
    if request.method == "POST":
        form = AddPhotosForm(request.POST, request.FILES)
        if request.POST.get('another'):
            if form.is_valid():
                cleaned_image = form.cleaned_data['image']
                cleaned_rental = form.cleaned_data['rental']
                current_rental = cleaned_rental

                pic = RentalPicModel(image=cleaned_image, rental=cleaned_rental)
                pic.save()

        current_photos = RentalPicModel.objects.filter(rental=current_rental)
        current_photos = [rental.image for rental in current_photos]
        for photo in current_photos:
            print photo

    context = {
        'form' : form,
        'photos' : current_photos,
    }

    return render(request, "add_photos.html", context)

这里print语句的输出(上传一张照片后)是:pics/originals/DSC_1376.jpg我可以看到文件已保存到该位置。

add_photos.html

    <div class="container">
        <h1>Upload your photos here.</h1>
        <br>
        <div class='row'>
            <form method="POST" action="" enctype="multipart/form-data"> {% csrf_token %}
                {{ form|crispy }}
                <div class='col col-xs-3'></div>
                <div class='col col-xs-3'>
                    <input class="btn btn-block btn-info" name="another" type="submit" value="Save and Add Another">
                </div>
                <div class='col col-xs-3'>
                    <input class="btn btn-block btn-primary" name="finish" type="submit" value="Save and Finish">
                </div>
                <div class="col col-xs-3"></div>
            </form>
        </div>

        {% if photos|length > 0 %}
            <h2>Uploaded photos:</h2>
            {% for photo in photos %}
                <div class='row'>
                    <img src="{{ photo.url }}" alt="">
                </div>
            {% endfor %}
        {% endif %}
    </div>

当我检查<img>元素时,我看到src="/media/media_root/pics/originals/DSC_1376.jpg"它给了我一个http://127.0.0.1:8000/media/media_root/pics/originals/DSC_1376.jpg. 这对我来说似乎是正确的文件位置,但它仍然没有显示。

就像我说的那样,在我看来,一切似乎都是在 Django 文档和我在 SO 上阅读的所有其他问题中描述的。我错过了什么?

先感谢您。

编辑

STATICFILES_DIRS对于上传的媒体,我是否需要修改我的设置?这是我现在所拥有的:

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static_files"),
)

这是我放置所有 CSS 和 javascript 文件的地方。

4

2 回答 2

2

我的网址是问题所在。当它试图检索媒体文件时,它url(r'^', profiles.views.home, name='home')在匹配任何媒体 url 之前匹配。一个简单的$修复它:

url(r'^$', profiles.views.home, name='home')
于 2016-01-29T16:47:40.143 回答
2

您忘记连接MEDIA_URL{{ photo.url }}

尝试:

<img src="{% get_media_prefix %}{{ photo.url }}" alt="">

更多关于{% get_media_prefix %} 这里的文档。

于 2016-01-27T21:44:19.913 回答