I want to enable my users to change their profile picture. When uploading a photo, I am redirected to the success page but the photo is not uploaded to the folder and the associated field is blank. Note that if a user already had a photo, it resets the field to blank so after submitting the form, the user has no photo anymore.
My guess is that the form.save(commit=False) does not upload the photo nor update the field as it should but I do not understand why !
Here is the model, view and form :
The Profil model:
class Profil(models.Model):
user=models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
photo_profil=models.ImageField(null=True,blank=True,upload_to='img/profils', verbose_name="Photo de profil", help_text="La taille du fichier doit être inférieure à {0}Mo. Seules les extensions .png, .jpeg et .jpg sont acceptées.".format(str(int(MAX_UPLOAD_SIZE/1000000))))
cours_valides=models.CharField(blank=True,max_length=255,validators=[int_list_validator])
niveau_valides=models.CharField(blank=True,max_length=255,validators=[int_list_validator])
def __str__(self):
return "Profil de {0}".format(self.user.username)
The ModelForm:
class PhotoForm(forms.ModelForm):
class Meta:
model=models.Profil
fields=('photo_profil',)
def clean_photo(self):
photo=self.cleaned_data.get('photo_profil')
if photo.size>settings.MAX_UPLOAD_SIZE:
raise forms.ValidationError(_("Le fichier envoyé depasse la limite de %sMo.".format(str(settings.MAX_UPLOAD_SIZE/1000000))))
return photo
And the view :
@login_required()
def change_photo(request):
if request.method=="POST":
form=forms.PhotoForm(request.POST,request.FILES)
if form.is_valid():
profil=form.save(commit=False)
profil.user=request.user
profil.save()
return redirect('espace_personnel')
else:
form=forms.PhotoForm()
return render(request,'utilisateurs/registration/change_photo.html',{'form':form})
Finally the template:
{% block item %}
<h3> Modifier sa photo de profil </h3>
<hr>
<div class="row">
<div class="col-lg-4">
<img src="{{user.profil.photo_profil_url}}" alt="{{user.username}}" class="img-responsive"/>
</div>
<div class="col-lg-8">
<h5>Photo actuelle</h5>
<p class="text-justify"> Votre photo n'est visible pour les autres utilisateurs qu'à côté des commentaires que vous laissez sur le site.</p>
</div>
</div>
<hr>
<form method="post">
{% csrf_token %}
<div class="form-group">
{{form.photo_profil}}
</div>
<p class="alert alert-info">{{form.photo_profil.help_text}}</p>
<button type="submit" class="btn btn-primary">Envoyer</button>
</form>
<hr>
{% endblock item %}
I have a read a few topics already but without success.
Thank you in advance for your help,
Matthieu
Make sure that you have MEDIA_ROOT
and MEDIA_URL
specified in your settings.py
file.
Also, add these lines in urls.py
:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Apart from that, in html form
, add enctype="multipart/form-data
in <form>
tag, like this:
<form method="post" enctype="multipart/form-data">
Make sure you have all these correct in your django app.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With