Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django'替代品;s image.url方法?_Python_Django_Image_Inline Formset - Fatal编程技术网

Python Django'替代品;s image.url方法?

Python Django'替代品;s image.url方法?,python,django,image,inline-formset,Python,Django,Image,Inline Formset,我正在使用inlineformset,这样用户可以一次上载多个图像。图像已保存,功能与预期一致,前端除外。当我使用类似于{form.image}的方法在我的表单集中循环时,我可以清楚地看到我的图像被保存了,当我单击url时,我被重定向到上传的文件。问题似乎是,当我尝试将图像的url设置为图像元素的src时,Absolute url没有存储 尝试在标记中记录媒体URL和媒体根目录不会产生任何结果 设置.py BASE_DIR = os.path.dirname(os.path.dirname(os

我正在使用inlineformset,这样用户可以一次上载多个图像。图像已保存,功能与预期一致,前端除外。当我使用类似于{form.image}的方法在我的表单集中循环时,我可以清楚地看到我的图像被保存了,当我单击url时,我被重定向到上传的文件。问题似乎是,当我尝试将图像的url设置为图像元素的src时,Absolute url没有存储

尝试在
标记中记录媒体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'),
] 
url.py

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.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)
views.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)
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)
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 %}
{%block main%}
{%csrf_令牌%}
{{gallery\u inlineformset.management\u form}
{对于gallery_inlineformset%}中的gallery_表单为%
{{gallery_form.image}
{{MEDIA_ROOT}}

{{MEDIA_URL}}

{%endfor%} {%endblock%}
同样,当我尝试:

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


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

使用
并确保
图像
不是

url.py中添加此行


urlpatterns+=static(settings.MEDIA\u URL,document\u root=settings.MEDIA\u root)
无需在图像地址之前添加
{{MEDIA\u URL}}
。因为默认情况下,它会在图像url路径之前添加
/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.conf导入设置的

如果设置为.DEBUG:
urlpatterns+=模式(“”,
(r'^media/(?P.*)$,'django.views.static.service'{
“document_root”:settings.MEDIA_root})
另外,当尝试在django模板中打印图像url时,请按如下方式处理图像不存在的情况:

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

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

<img src="{% if gallery_form.image %}{{ gallery_form.image.url }}{%else%} <default-image-path-here> {%endif%}"
views.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)
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>

{%csrf_令牌%}
{{gallery\u inlineformset.management\u form}
{对于gallery_inlineformset%}中的gallery_表单为%
{{gallery_form.image}
{%如果gallery_form.image不是None%}
下图应为:

{%endif%} {%endfor%}

此外,由于我不再使用bulk_create(),我最终替换了原始帖子中的大部分代码。

这似乎会有所帮助?@SamHollenbach我已经使用过该线程(以及其他许多线程)作为参考。不幸的是,我之所以在这里是因为我找不到解决方案。也许我忽略了什么?我刚刚测试过,图像不是没有。仍然存在相同的问题。你的
图像是否在媒体文件夹中?是的,所有图像都上载到指定的文件夹。@Shafikurrahmanshaonca你能调试你的图像
吗rc
get-fact?我不太确定如何做到这一点。我只知道当我使用Chrome进行检查时,我会得到“unknown”。对不起,我忘了添加我已经有了url.py设置。我已经更新了我的问题,以便您可以看到它。仍然无法解决该问题。另外,感谢您提供有关检查不存在图像的提示。