简体   繁体   中英

How can I get the url of a Django ImageField?

I am using a modelformset_factory method with forms containing only an ImageField. The Model the forms are based on contains a user field that has a many-to-one relationship with a User Model that extends AbstractUser( See Extending User Model with Abstract User ). Currently, each instance of a user has a correlating User Profile, but I would also like to allow the user to upload a gallery of images to their profile.

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})

Template

<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>

The problem I'm have is that using {{ form.image }} produces this result: 在此处输入图片说明

... and using {{ form.image.url }} within an image's source tag produces absolute nothing at all. When I inspect the element I contain it in, it states the source is unknown. Obviously, the images are being saved in the DB as I'd like, but I can't get the .url functionality to work. And YES, I do have the media root an all defined:

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)

Try to replace your code with the following code:

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

with:

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

Try to replace your code with the following code:

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})

Template

<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" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM