Alek H.
Alek H.

Reputation: 129

How to save path to image when I create object using forms

I have a such model in django 1.6:

class Instance(models.Model):
  ...
  image = models.ImageField(upload_to='flats_photo',null=True, blank=True)
  ...

Form:

class InstanceForm(ModelForm):
    class Meta:
       model = Instance
       fields=[...,'image',...]

When I create new object I use such view:

def add_instance(request):
   if request.POST:
      form=InstanceForm(request.POST)
      if form.is_valid():
         f = InstanceForm(request.POST)
         new_instance=f.save()

   else:form=InstanceForm()

   locals().update(csrf(request))
   return render_to_response(...)

All fields of new object create, but not field image.There is no image. In django admin I see: Image no file selected. Everything work good when i add object from admin. How to solve this problem

Upvotes: 0

Views: 91

Answers (1)

Stuart Leigh
Stuart Leigh

Reputation: 856

the file data isn't in request.POST it's in request.FILES

https://docs.djangoproject.com/en/dev/topics/http/file-uploads/#handling-uploaded-files-with-a-model

Change your function to something like

def add_instance(request):
   if request.POST:
      form=InstanceForm(request.POST, request.FILES)
      if form.is_valid():
         new_instance=form.save()
   else:
      form=InstanceForm()

   locals().update(csrf(request))
   return render_to_response(...)

Upvotes: 1

Related Questions