Картинка профиля не отображается

Я могу загрузить изображение профиля, и оно попадает в базу данных. У меня есть "print(profile.profile_picture)" в моем views.py, который правильно выводит текущую картинку профиля в консоль при сохранении. Однако по какой-то причине картинка профиля не отображается, мой "{% if profile.profile_picture %}" в profile.html даже ничего не подхватывает. [media]

printed profile picture

profile picture

VIEWS.PY=

@login_required
def profile(request):
    profile, created = Profile.objects.get_or_create(user=request.user)
    print(profile.profile_picture)
    if request.method == 'POST':
        form = ProfileForm(request.POST, request.FILES, instance=profile)
        if form.is_valid():
            form.instance.user = request.user
            form.save()
            return redirect('base:profile')  # Redirect to the home page after form submission
    else:
        form = ProfileForm(instance=profile)
    
    return render(request, 'profile.html', {'form': form})

PROFILE.HTML=

    <div class="ProfilePage">
        <form method="POST" enctype="multipart/form-data" class="profile-form">
            {% csrf_token %}
            
            <div class="form-group">
                <label for="id_username">Username:</label>
                <input type="text" id="id_username" value="{{ request.user.username }}" readonly>
            </div>

            <div class="form-group">
                <label for="id_bio">Bio:</label>
                <textarea id="id_bio" name="bio" rows="4" cols="50" required>{{ form.bio.value }} </textarea>
            </div>

            <div class="form-group">
                <label for="id_profile_picture">Profile Picture:</label>
                <input type="file" id="id_profile_picture" name="profile_picture" accept="image/*">
            </div>
            
            {% if profile.profile_picture %}
                <div class="form-group">
                    <label>Profile Picture Preview:</label><br>
                    <img src="{{ profile.profile_picture.url }}" alt="Profile Picture" style="max-width:     500px;">
                </div>
            {% endif %}
    
            <button type="submit" class="btn-submit">Save</button>
            
            
        </form>
    </div>                                                                                                      

FORMS.PY=

     from django import forms
     from .models import Profile

     class ProfileForm(forms.ModelForm):
       class Meta:
         model = Profile
         fields = ['bio', 'profile_picture'] 

URLS.PY =

    from django.contrib import admin
    from django.urls import path, include
    from django.conf import settings
    from django.conf.urls.static import static
    from base import views  # Import views from the base app

    urlpatterns = [
    path('admin/', admin.site.urls),
    path("", include(("base.urls", "base"), namespace="base")),  # Include     
 app-level URLs with a namespace
    path('profile/settings/', views.profile_settings, name='profile_settings'),
    path('profile/<str:username>/', views.public_profile, name='public_profile'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

MODELS.PY =

    from django.db import models
    from django.contrib.auth.models import User
    from django.contrib.auth import get_user_model
    import uuid
      from datetime import datetime

    User = get_user_model()

    class Profile(models.Model):
          user = models.OneToOneField(User, on_delete=models.CASCADE)
          bio = models.TextField(blank=True)
          profile_picture = models.ImageField(upload_to='profile_pics',       
 blank=True)

     class Post(models.Model):
          id = models.UUIDField(primary_key=True, default=uuid.uuid4)
          user = models.CharField(max_length=100)
          image = models.ImageField(upload_to='post_images')
          caption = models.TextField()
          created_at = models.DateTimeField(default=datetime.now)
          no_of_likes = models.IntegerField(default=0)

          def __str__(self):  
              return self.user

Я могу предоставить больше информации, я немного запутался, почему это не работает.

Добавили ли вы эти коды в конце строки в ваш urls.py в папке настроек проекта и какой путь установлен в MEDIA_URL и MEDIA_ROOT

# settings.py
MEDIA_URL = "media/"
MEDIA_ROOT = BASE_DIR / "media"
# root urls.py  
if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

если это не помогло, пожалуйста, покажите ваш код в models.py

Вернуться на верх