0

I'm trying to work out how I can prevent losing edits to ImageField details should a form fail validation. Currently if the form fails validation or if I reload the page any image paths that I have browsed to will be lost and the default 'No file chosen' is redisplayed.

In a scenario where many image paths are being browsed to it would lead to an annoyance if they were all lost because another part of the form failed validation.

I've browsed through all the StackOverflow questions tagged with Django-ImageField and have looked through the Django docs but I've not spotted anything that gives a clear explanation how a selected path can be preserved.

Here's a very simple project that demonstrates this problem:

file_uploads project

urls.py

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = patterns('',
    url(r'^admin/', include(admin.site.urls)),
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

user_profile app

admin.py

from django.contrib import admin
from user_profile.models import Profile 

class ProfileAdmin(admin.ModelAdmin):
    list_display = ('name',)

admin.site.register(Profile, ProfileAdmin)

models.py

from django.db import models

class Profile(models.Model):
    name = models.CharField(max_length=64,
                            verbose_name='Your Name')
    number = models.DecimalField(max_digits=3,
                                 decimal_places=1,
                                 verbose_name='Your Number')
    photo = models.ImageField(upload_to='avatar',
                              verbose_name='Your Picture')
    def get_absolute_url(self):
        return reverse(user_profile.views.profile, args=[str(self.id)])

Appreciate any feedback that anyone could give about this.

jayuu
  • 443
  • 1
  • 4
  • 17
  • I'm afraid you can't achieve this directly. Check http://stackoverflow.com/questions/1696877/how-to-set-a-value-to-a-file-input-in-html. That's why Django can not help here, currently. – okm May 27 '13 at 14:49
  • This is the way browsers are implemented for security reasons. If you want to override it, you might want to consider using sessions and populate them in your code on load. – karthikr May 27 '13 at 15:13
  • @karthikr Sessions sounds like it could be useful but perhaps another way would be to have the user successfully complete the rest of the form before providing the option to upload images. It feels clunky though. – jayuu May 27 '13 at 16:55

0 Answers0