替代Django的image.url方法?

问题描述 投票:0回答:3

我使用的是inlineformset,以便用户可以一次上传多张图片。图像被保存和功能是如预期,除了在前端侧。当我依次通过我的表单集用类似的方法{{形式。图像}},我可以清楚地看到我的形象被保存,当我点击链接,我重定向到上传的文件。这个问题似乎是在absoulte网址不被存储时,我尝试把图像的URL作为图像元素的SRC。

尝试登录MEDIA_URL和MEDIA_ROOT在<p>标签产生任何结果。

settings.朋友

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'),
] 

URLs.朋友

from django.conf.urls import url, include
from . import views
from django.conf.urls.static import static
from django.conf import settings
app_name = 'Accounts_Namespace'
urlpatterns = [
    url(r'^$', views.Register, name='Accounts_Register'),
    url(r'^change-password/$', views.ChangePassword, name="Accounts_Change_Password"),
    url(r'^login/$', views.Login, name='Accounts_Login'),
    url(r'^logout/$', views.Logout, name='Accounts_Logout'),
    url(r'^profile/$', views.ViewProfile, name='Accounts_View_Profile'),
    url(r'^profile/edit/$', views.EditProfile, name="Accounts_Edit_Profile"),
    url(r'^school/', include('student_map_app.urls', namespace="Student_Maps_Namespace")),

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

models.朋友

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)

views.朋友

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)

editprofile.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 }}">

我得到的“未知”作为源的价值,但我可以点击链接“{{gallery_form.image}}”生成并查看已上传的图像。试图登录这两个“MEDIA_URL”和“MEDIA_ROOT”产生任何结果。不太清楚其中的问题所在。

python django image inline-formset
3个回答
0
投票

无需图像的地址之前添加{{MEDIA_URL}}。因为默认情况下它会你的图片的URL路径前添加/media

此外,一定要所有的路径开始media添加到您的网址。

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时,处理该图像不存在这样的情况:

<img src="{% if gallery_form.image %}{{ gallery_form.image.url }}{%else%} <default-image-path-here> {%endif%}"

0
投票

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

urls.py加入这一行

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


0
投票

虽然我不明白,为什么我不能使用的.url()方法Django的预定义了,我也不过,最终使用在我的前面的问题向我提出另一种解决方案用户。基本上,用户已经上传的图片,我们让他们存储在一个数据库后,我们做一个变量存储这些图像的URL属性,并从模板访问该变量。它看起来是这样的:

views.朋友

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)

template.html

<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, this is not he image var from views.py -->
                    {% if gallery_form.image is not None %}
                        <p>The image should be below:</p>
                        <img src="{{ gallery_form.initial.image_url }}">
                    {% endif %}
                </div>
            {% endfor %}
            <input type="submit" name="gallery-submit" value="Submit" />
        </form>

另外,我最终取代了大部分的代码从原来的岗位作为我不再使用bulk_create()。

© www.soinside.com 2019 - 2024. All rights reserved.