1

I have this weird problem in Django.

I have a form with several text fields and a ImageField. In an edit view, I want the form to be prepopulated with values from an instance, retrieved from the database.

The below code seems to work:

form = UserForm(request.POST or None, instance=instance)

It prepopulates my form with the text fields. The ImageField is also prepopulated, but no matter what new image I choose, it doesn't update after the submission of the form.

I've tried:

form = UserForm(request.POST or None, request.FILES, instance=instance)

which, for some reason, causes every field in the form to be empty with the exception of the ImageField, which I can now change.

What I want to achieve is: the text fields to be prepopulated, as well as the ImageField. I should be able to change the ImageField.

Any thoughts on that?

ExplodingTiger
  • 327
  • 2
  • 6
  • 18
  • http://stackoverflow.com/questions/2039749/when-editing-an-object-in-django-the-imagefield-is-not-populated – Shang Wang Nov 15 '15 at 00:48
  • Doesn't really solve my problem - I don't want any thumbnails. My problem is that I can't upload a new image file. Also, I am printing each field individually (not using form.as_p). – ExplodingTiger Nov 15 '15 at 01:21

2 Answers2

3

One example the save data with request.files and instance with forms.

def LocationEdit(request, pk):

locations = Location.objects.get(pk=pk)

form = LocationForm(request.POST or None, instance=locations)

if request.method == 'POST':

    form = LocationForm(request.POST or None, request.FILES or None, instance=locations)
    print(form)
    if form.is_valid():

        form.save()

        messages.success(request, "I saved it successfully")
        return redirect('location:location_list')

types = Location.STATUS

return render(request, 'backend/location/edit.html', {'form' : form, 'locations' : locations, 'types' : types})
2

just try

form = UserForm(request.POST,request.FILES OR None)
Thameem
  • 3,426
  • 4
  • 26
  • 32