0

I have a model:

class Dialogue(models.Model):
    ...
    avatar = models.ImageField(upload_to=conference_directory_path, blank=True)
    ...

And a ModelForm for it:

class CreateConferenceForm(forms.ModelForm):
    class Meta:
        model = Dialogue
        fields = ['name', 'participants', 'avatar']
    ...

My question is do I need to make a special function for handle uploaded avatar like:

def handle_uploaded_file(file):
    with open(some_file_path, 'wb+') as destination:
        for chink in file.chunks():
            destination.write(chunk)

Or I can without fear simply use save method of ModelForm? And if I can't - where is better place for this function: in view or in forms? And how does it look - saving an avatar using handle function? At the beggining I handle an uploaded file using handle function and then how can this uploaded file be added to imagefield?

Alexander Shpindler
  • 811
  • 1
  • 11
  • 31

1 Answers1

0

The ModelForm will handle it for you, as long as your form uses method="post" and you have enctype="multipart/form-data" set on your form. You may also want to set null=True on the model field, otherwise the instance will not save when you don't provide an image.

voodoo-burger
  • 2,123
  • 3
  • 22
  • 29
  • Thank you. Therefore in usual Form I need to use handle function, right? If yes, could you please answer for the same questions about usual Form :) – Alexander Shpindler Jan 27 '17 at 13:14
  • @AlexanderShpindler here it is: http://stackoverflow.com/questions/5871730/need-a-minimal-django-file-upload-example?rq=1 – voodoo-burger Jan 27 '17 at 13:17