0

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

1 Answer 1

1

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(...)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.