Django的替代品图像.url方法?

2024-05-03 12:44:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用了一个inlineformset,这样用户可以一次上传多个图像。图像被保存,功能如预期,除了前端。当我用一个类似{form的方法遍历我的formset时。图像}},我可以清楚地看到我的图像被保存,当我点击url时,我被重定向到上传的文件。问题似乎是,当我试图将图像的url设置为image元素的src时,绝对url没有被存储。在

尝试在<p>标记中记录媒体URL和媒体根目录不会产生任何结果。在

在设置.py在

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')    
ROOT_URLCONF = 'dashboard_app.urls'
STATIC_URL = '/static/' 
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),
] 

在网址.py在

^{pr2}$

在模型.py在

class Gallery(models.Model):
id = models.AutoField(primary_key=True)
user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
image = models.ImageField(upload_to="gallery_images")
uploaded = models.DateTimeField(auto_now_add=True)

在视图.py在

def EditProfile(request):
user = request.user

galleryInlineFormSet = inlineformset_factory(get_user_model(), Gallery, form=GalleryForm)
selectedUserGallery = Gallery.objects.filter(user=user).order_by('uploaded')
userGallery_initial = [{'image': selection.image} for selection in selectedUserGallery] # Using this syntax because formset initials accept dictionaries

if request.method == "POST":
    profile_form = ProfileEditForm(request.POST, instance=request.user)
    gallery_inlineformset = galleryInlineFormSet(request.POST, request.FILES)   # Essentially, we're passing a queryset

    if profile_form.is_valid() and gallery_inlineformset.is_valid():
        # Altering the User model through the UserProfile model's UserProfileForm representative
        user.first_name = profile_form.cleaned_data['first_name']
        user.last_name = profile_form.cleaned_data['last_name']
        user.save()

        new_images = []

        for gallery_form in gallery_inlineformset:
            image = gallery_form.cleaned_data.get('image')
            if image:
                new_images.append(Gallery(user=user, image=image))
        try:
            Gallery.objects.filter(user=user).delete()
            Gallery.objects.bulk_create(new_images)
            messages.success(request, 'You have updated your profile.')
        except IntegrityError:
            messages.error(request, 'There was an error saving your profile.')
            return HttpResponseRedirect('https://www.youtube.com')

else:
    profile_form = ProfileEditForm(request.user)
    gallery_inlineformset = galleryInlineFormSet(initial=userGallery_initial)

args = { 'profile_form':profile_form, 'gallery_inlineformset':gallery_inlineformset }
return render(request, 'accounts_app/editprofile.html', args)

在编辑配置文件.html在

    {% block main %}
<section class="Container">
    <section class="Main-Content">
        <form id="post_form" method="POST" action='' enctype='multipart/form-data'>
            {% csrf_token %}
            {{ gallery_inlineformset.management_form }}
            {% for gallery_form in gallery_inlineformset %}
                <div class="link-formset">
                    {{ gallery_form.image }}    <!-- Show the image upload field -->
                    <p>{{ MEDIA_ROOT }}</p>
                    <p>{{ MEDIA_URL }}</p>
                    <img src="/media/{{gallery_form.image.image.url}}">
                </div>
            {% endfor %}
            <input type="submit" name="submit" value="Submit" />
        </form>
    </section>
</section>
{% endblock %}

再次,当我尝试:

<img src="{{ MEDIA_URL }}{{ gallery_form.image.url }}">

我得到一个值“unknown”作为源,但是我可以单击“{gallery”的链接_窗体.图像}}“生成并查看上载的图像。尝试同时记录“MEDIA_URL”和“MEDIA_ROOT”不会产生任何结果。不太清楚问题出在哪里。在


Tags: path图像imageformurlosmodelsrequest
3条回答

无需在图像地址前添加{{MEDIA_URL}}。因为默认情况下,它将在图像url路径之前添加/media。在

还要确保将所有以media开头的路径添加到您的url中。在

from django.conf import settings

if settings.DEBUG:
    urlpatterns += patterns('',
        (r'^media/(?P<path>.*)$', 'django.views.static.serve', {
        'document_root': settings.MEDIA_ROOT}))

另外,当尝试在django模板中打印图像url时,请处理图像不存在的情况,如下所示:

^{pr2}$

虽然我不明白为什么我不能使用Django预先定义的.url()方法,但是我最终还是使用了一个用户在我之前的问题中向我建议的另一个解决方案。基本上,在用户上传图片并将其存储在数据库中之后,我们创建一个变量来存储这些图像的URL属性,然后从模板访问该变量。看起来像这样:

在视图.py在

selectedUserGallery = Gallery.objects.filter(user=user) # Get gallery objects where user is request.user
userGallery_initial = [{'image': selection.image, 'image_url':selection.image.url} for selection in selectedUserGallery if selection.image]
if request.method == "GET":
    print("    GET REQUEST: PRESENTING PRE-EXISTING GALLERY IMAGES.   -")
    profile_form = ProfileEditForm(request.user)
    gallery_inlineformset = galleryInlineFormSet(initial=userGallery_initial)

在模板.html在

^{pr2}$

另外,我最后替换了原帖子中的大部分代码,因为我不再使用bulk iu create()。在

使用<img src="{{ gallery_form.image.url }}">并确保image不是{}

在你的urls.py中添加这一行

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

相关问题 更多 >