Home > Software design >  Django Picture showing as broken when referenced in template
Django Picture showing as broken when referenced in template

Time:09-30

I am trying to create a settings page for user profiles and I have hit a roadblock. I included a profile image inside of my User model and when trying to reference said ImageField in my profile template the image shows up as broken. Firstly, everything else related to the storing of a profile image works. When an account is created, the default image saves and same with using the upload picture form. The issue comes when trying to display the current profile picture through the model's url and the image shows up as broken.

models.py

class Profile(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
id_user = models.IntegerField()
bio = models.TextField(max_length=300, blank=True)
profileimg = models.ImageField(upload_to='profile_images', default='blank-profile.jpg')
verified = models.BooleanField(default=False)

def __str__(self):
    return self.user.username

views.py

def settings(request):
user_profile = Profile.objects.get(user=request.user)

if request.method == "POST":

    if request.FILES.get('image') == None:
        image = user_profile.profileimg
        bio = request.POST['bio']

        user_profile.profileimg = image
        user_profile.bio = bio
        user_profile.save()

    if request.FILES.get('image') != None:
        image = request.FILES.get('image')
        bio = request.POST['bio']

        user_profile.profileimg = image
        user_profile.bio = bio
        user_profile.save()
    return redirect('settings')
    return render(request, 'settings.html', {'user_profile': user_profile})

Section of html file that tries to show image

<img width="100" heigh="100" src="{{ user_profile.Profileimg.url }}" />

I have also added all of the necessary MEDIA_URL/root settings and have tried adding said settings to my urls.py but none of it worked. When viewing the settings page it only shows the default icon for a broken image. Please and thank you for any help.

enter image description here

CodePudding user response:

your url has Profileimg, try profileimg.

CodePudding user response:

So I did not know this, but I guess when settings.py DEBUG = True Django doesn't display media files. I had to add this to the urls.py of my project:

if settings.DEBUG:
urlpatterns  = static(settings.MEDIA_URL,
                      document_root=settings.MEDIA_ROOT)
  • Related