如何获取Django ImageField的URL?

时间:2018-05-07 03:02:29

标签: python django django-forms image-gallery

我正在使用一个只包含ImageField的表单的modelformset_factory方法。表单所基于的模型包含一个用户字段,该用户字段与扩展AbstractUser(See Extending User Model with Abstract User)的用户模型具有多对一关系。目前,用户的每个实例都具有关联的用户配置文件,但我还希望允许用户将图像库上传到其配置文件。

models.py

class Gallery(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) 
    image = models.ImageField(upload_to='user_gallery', blank=True, null=True)

    def create_gallery(sender, **kwargs):
        if kwargs['created']:
            user_gallery = Gallery.objects.create(user=kwargs['instance'])
            user_gallery.save();
post_save.connect(create_gallery, sender=User)

forms.py

class GalleryForm(forms.ModelForm):
image = forms.ImageField(label='FormImage')
class Meta:
    model = Gallery
    fields = ['image']

views.py

def EditProfile(request):
    GalleryFormSet = modelformset_factory(Gallery, form=GalleryForm, extra=3, max_num=3)
    if request.method == "POST":
        formset = GalleryFormSet(request.POST, request.FILES)
        if formset.is_valid():
            for form in formset.cleaned_data:
                my_image = form['image']
                photo = Gallery(user=request.user, image=my_image)
                photo.save()

            return render(request, 'user_handler/editprofile.html', {'formset': formset})
    else:
        formset = GalleryFormSet()
    return render(request, 'user_handler/editprofile.html', {'formset': formset})

模板

<form id="post_form" method="post" action="" enctype="multipart/form-data">
        {% csrf_token %}
        {{ formset.management_form }}

        {% for form in formset %}
            {{form.image}}
            <img src="{{form.image.url}}"/>
        {% endfor %}
        <input type="submit" name="submit" value="Submit" />
</form>

我遇到的问题是使用{{form.image}}会产生以下结果:enter image description here

...并且在图像的源标记中使用{{form.image.url}}会产生绝对的内容。当我检查包含它的元素时,它表明源是未知的。显然,我想将图像保存在数据库中,但我无法使用.url功能。是的,我确实有媒体根定义:

settings.py

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/static/'
MEDIA_URL = '/media/'   
MEDIA_ROOT = os.path.join(BASE_DIR, 'HighlightPage_Project/media')  

urls.py

urlpatterns = [
url(r'^$', views.Login_Redirect),
url(r'^account/', include('user_handler_app.urls')),
url(r'^admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

2 个答案:

答案 0 :(得分:0)

尝试用以下代码替换您的代码:

views.py

def EditProfile(request):
    GalleryFormSet = modelformset_factory(Gallery, form=GalleryForm, extra=3, max_num=3)
    if request.method == "POST":
        formset = GalleryFormSet(request.POST, request.FILES)
        if formset.is_valid():
            for form in formset.cleaned_data:
                my_image = form['image']
                photo = Gallery(user=request.user, image=my_image)
                photo.save()

            return render(request, 'user_handler/editprofile.html', {'formset': formset})
    else:
        user_images = Gallery.objects.filter(user=request.user)
        initial_images = [{'image': i.image, 'image_url': i.image.url} for i in user_images if i.image]
        formset = GalleryFormSet(initial=initial_images)
    return render(request, 'user_handler/editprofile.html', {'formset': formset})

模板

<form id="post_form" method="post" action="" enctype="multipart/form-data">
    {% csrf_token %}
    {{ formset.management_form }}

    {% for form in formset %}
        {{form.image}}
        <img src="{{form.initial.image_url}}"/>
    {% endfor %}
    <input type="submit" name="submit" value="Submit" />

答案 1 :(得分:0)

尝试用以下代码替换您的代码:

<img src="{{form.image.url}}"/>

具有:

<img src="{{form.instance.image.url}}"/>