sumit
sumit

Reputation: 15464

how to handle imagefield update in django form

I have following models for category

class Category(models.Model):
   name = models.CharField(max_length=30)
   is_active=models.BooleanField()
   photo=models.ImageField(upload_to='category')
   def __unicode__(self):
     name = str(self.name)
     return name
  def image(self):
    return self.photo or 'DEFAULT_PIC.jpg'
  class Meta:
        permissions = (
            ('category','Category'),
            ('view_category', 'View category'),
        )

My form class is as follows

class categoryForm(forms.Form):
    name = forms.CharField(widget=forms.TextInput(attrs={'class':'box'}),max_length=32,label='Category',required=True)
    is_active = forms.BooleanField(required=False)
    id = forms.CharField(widget=forms.HiddenInput,required=False)
    photo = forms.FileField(
        required=False,
        label='Select an Image',
        help_text='max. 4 megabytes'
   )

It is working perfect for insert and update both, now i am trying to load the image which has already been upload in the form (say i have already added one category with image , now i want to upload another image, so i am trying to show the preview of previously uploaded image)

I passed the data in the view and tried few hack in forms

formdata = categoryForm({'name':p.name,'is_active':p.is_active,'id':p.id,'photo':p.image()})

In form i made modification as below

def __init__(self, data=None, **kwargs):
#    pass
     super(categoryForm, self).__init__(data, **kwargs)
     if self.data['photo']!='':
        self.fields['uploaded_photo'] =forms.CharField(widget=forms.TextInput,required=False,label=mark_safe('<img src="/media/%s" height="100">'%(self.data['photo'])))
        #self.fields['uploaded_photo'].widget.attrs['value']=self.data['photo']

Now it is perfectly showing previously uploaded image on label .

After that i tried to upload another image but it shows following error

TypeError at /update/category/

init() takes at most 2 arguments (3 given)

Script to handle image upload is as follows

formdata = categoryForm(request.POST,request.FILES)
        if formdata.is_valid():
            cd = formdata.cleaned_data
            p1=Category()
            p1.id=cd['id']
            p1.name=cd['name']
            p1.is_active=cd['is_active']
            p1.photo=cd['photo']
            p1.save()

Please let me know what is happening here

Upvotes: 0

Views: 1741

Answers (1)

Zain Khan
Zain Khan

Reputation: 3793

Try making life easy by using the ImageField

class ImageField(**kwargs)¶

  • Default widget: ClearableFileInput
  • Empty value: None
  • Normalizes to: An UploadedFile object that wraps the file content and file name into a single object.
  • Validates that file data has been bound to the form, and that the file is of an image format understood by PIL.
  • Error message keys: required, invalid, missing, empty, invalid_image

    Using an ImageField requires that the Python Imaging Library is installed.

    When you use an ImageField on a form, you must also remember to bind the file data to the form.

Check out the complete documentation here

Upvotes: 1

Related Questions