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?
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.