lundi 23 mars 2015

How to get an image form field to update only if a new file has been chosen in django?

I have a custom profile form with an image field where users can upload a profile picture along with some other fields. It works fine so far. The problem is, when submitting the form, it always uploads and updates the field, even when a user didn't choose a file. So a user has submitted the form and uploaded a picture. He/she then comes back at a later point to update some other field, but not the picture. After submitting the form the profile pic is gone and has resetted to default. How do I get the image field to update only if a new file has been chosen?


modesl.py



class Profil(models.Model):
def content_file_userpic(instance, filename):
return '/'.join(['pics', instance.user.username, filename])

user = models.OneToOneField(User, primary_key=True)
user_pic = models.ImageField(upload_to=content_file_userpic, blank=True, verbose_name='Foto', default='user_pic_default.png')


forms.py



class ProfilForm(ModelForm):
user_pic = forms.ImageField(label='Foto',required=False, widget=forms.FileInput)

Aucun commentaire:

Enregistrer un commentaire