1

Im trying to submit a form with some textfields and an imagefield. And save it as a new model object. Cant get it to work so im going over each part from the start now..

How do i handle (just saving it) the imagefield in my views? Do i need to write an extra handler? It's not a modelform but a regular form. Where does PIL/PIllow come into this. Should I import it? Can i clean the imagefield?

I've been trying this:

def UploadThis(request):

    if request.method == 'POST':
        form = TestForm(request.POST, request.FILES) 
        response = {}

            if form.is_valid():
                response["status"] = "OK"

                justtesting = Newmodel()

                cd = form.cleaned_data

                justtesting.name = cd['name']
                justtesting.type = cd['type']
                justtesting.description = cd['description']
                justtesting.picture = request.FILES['picture']
                justtesting.save()

Model:

class Newmodel(models.Model):
    name = models.CharField(max_length=50)
    type = models.CharField(max_length=50)
    description = models.CharField(max_length=140, blank=True)
    picture = models.ImageField(upload_to='images/testfiles', blank=True)

    def __unicode__(self):
        return self.name

Form:

class TestForm(forms.Form):

    name = forms.CharField(max_length=50)
    type = forms.CharField(max_length=50)
    description = forms.CharField(max_length=140)
    picture = forms.ImageField()


    def clean(self):
        cleaned_data = self.cleaned_data

        name = cleaned_data.get("name")
        description = cleaned_data.get("description")
        type = cleaned_data.get("type")

        return cleaned_data
user3199840
  • 525
  • 2
  • 13
  • 35
  • Can you paste your Form and Model? please – Victor Castillo Torres Feb 02 '14 at 20:45
  • Ok! Please have a look. I actually think it's something wrong with my js-function which submits the form but i need to know that it is like it should in the "views" end first because it's impossible to test and try otherwise. So please let me know if whats wrong here! thank you – user3199840 Feb 02 '14 at 21:00

1 Answers1

3

Your error is that you are trying to assign the image to the model field using request.POST, when you actually need to use form.cleaned_data like so:

justtesting.picture = form.cleaned_data['picture']

Your clean method on the form is not doing anything currently. You could do validation (although that is not neccessary) by using a clean method something like this:

def clean_image(self):
    image = self.cleaned_data.get('image', None) 
    if image:
        # do some validation, if it fails
        raise forms.ValidationError(u'Form error')
    return image

For an example that validates the image size see this question: https://stackoverflow.com/a/16425455/1744645

Using PIL/Pillow is not necessary and only required if you want to some form of image processing. You could have a save method on your model, for example to resize the image:

def save(self,force_insert=False, force_update=False, *args, **kwargs):

    # save everything else
    super(Newmodel, self).save(force_insert, force_update)

    if self.image:
         if self.image.width > 300 or self.image.height > 300:
             resize_image(self.image)

PIL/Pillow itself has the following basic operations that might be of interest:

img = PIL.open(PATH_TO_IMAGE)
img = img.resize((x, y), PIL.ANTIALIAS)
img = img.crop((0, 0, x, y))
img.save(path,quality=90)

But see http://effbot.org/imagingbook/pil-index.htm for the full docs.

trex
  • 3,848
  • 4
  • 31
  • 54
joshcarllewis
  • 371
  • 2
  • 3
  • Thank you so much! Thats what a call a GREAT answer!! (not getting much response here on stackoverflow) If you know jaquery/ajax submit with image fields please take a look at my not-working function. (been working in this for days now so im getting pretty desperate..) http://stackoverflow.com/questions/21503802/submit-form-django-form-with-imagefield-via-jquery-ajax-post – user3199840 Feb 02 '14 at 22:05
  • This answer helped me a lot! Now i can atleast submit the image with the normal submitbutton! So i know it' nothing wrong with the view handling anymore! – user3199840 Feb 03 '14 at 00:34