4

Currently I am using something like:

initialValues={
    'textField1':'value for text field 1',
    'textField2':'value for text field 2',
    'imageField': someModel.objects.get(id=someId).logo
    }

form = myForm(initial=initialValues)

When I call myForm as above, the initial values are displayed as expected: the textField1, textField2 and imageField (with the options Currently: linkToImage, Clear check box and Change: )

But when I save the form, there is nothing saved in the imageField field (checking the database and I see the imageField field blank).

I know that I miss something here, but I cannot figure out what. Any tips?

marlboro
  • 254
  • 6
  • 16
  • Have you specified [`upload_to`](https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.FileField.upload_to) in the model and `MEDIA_PATH` in your settings? ([Here](http://www.nitinh.com/2009/02/django-example-filefield-and-imagefield/) is a good post with a full example). – Jeremy Blanchard Jan 28 '12 at 20:42

2 Answers2

3

I solved my issue by assigning

request.FILES['imageField']=someModel.objects.get(id=someId).logo

just before I save the form. Yeey

marlboro
  • 254
  • 6
  • 16
0

You need to pass in the data to the form when creating it.

initialValues={
    'textField1':'value for text field 1',
    'textField2':'value for text field 2',
    'imageField': someModel.objects.get(id=someId).logo
    }
form = myForm(data=request.POST, initial=initialValues)

If you're not doing so already, I would suggest using class-based views. With a FormView you can easily override the get_initial_data() function, specify your values, and then let the view take care of what other things to pass on to the form to save it. If you're trying to save a model (which I think you are), check out the CreateView and UpdateView.

I could be more sure about this answer if I knew exactly how/when you were initializing that form.

  • It is exactly what I am doing. When creating myForm I assign the initial values ... then the form is shown through the template, the three fields are shown as expected. After I save the form I check the db and I can see that only textField 1 and 2 are saved, but the imageField is not. – marlboro Jan 28 '12 at 19:54