【问题标题】:Django returns only default image URLDjango 仅返回默认图像 URL
【发布时间】:2021-03-08 00:01:50
【问题描述】:

我是 Django 新手,正在构建一个简单的社交媒体类型应用程序来添加和查看帖子。

我正在使用管理员端为用户上传个人资料图片,效果很好。我还没有创建一个前端来上传个人资料图片。

我正在使用 PostgreSQL,我可以查询以查看保存在表中的正确 URL 以获取个人资料图像。但是当我尝试获取这些图像并渲染时,默认图像(在 models.py 中设置)总是会渲染。我可以从管理员端打开正确的图像,但 Django 只返回默认图像。

我的前端有 Javascript,我在其中使用 fetch API 来获取个人资料图片的 URL。它运行良好,只是它只返回默认图像。

请帮助我找出哪里出错了,或者为什么总是只显示“defaultpp.jpg”。我尝试在 models.py 和 views.py 中使用 print 语句,只看到返回的“defaultpp.jpg”的 URL。

models.py

def user_directory_path(instance, filename):
    return f'{instance.profile_user.id}/{filename}'

class User(AbstractUser):
    def __str__(self):
        return f"User ID: {self.id} Username: {self.username}"

class UserProfile(models.Model):
    profile_user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
    profile_picture = models.ImageField(upload_to = user_directory_path, blank=True, null=True, default='defaultpp.jpg')
    

    def __str__(self):
        return f"User: {self.profile_user} Username: {self.profile_user.username}"


    @property
    def get_profile_picture_url(self):
        if self.profile_picture and hasattr(self.profile_picture, 'url'):
            return self.profile_picture.url

settings.py

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

DEBUG = True

STATIC_URL = '/static/'

# Root and URL for uploaded files to be stored
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

views.py

def profile_image(request, user):
    
    user = User.objects.get(username=user)
    profile = UserProfile(profile_user=user)
    profile_picture_url = str(profile.get_profile_picture_url)

    return JsonResponse({"image": profile_picture_url}, safe=False)

profile_picture_url = str(profile.get_profile_picture_url) 每次都返回 'defaultpp.jpg' 的 URL,即使我在那里上传了一些其他图片

urls.py

from django.contrib import admin
from django.urls import include, path
from django.conf.urls.static import static
from django.conf import settings

urlpatterns = [
    path("admin/", admin.site.urls),
    path("", include("network.urls")),
]  + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

HTML 和 JS

<script>

    //funtion to fetch profile image for each post and add it to the media object
    function post_profile_image()
    {
        document.querySelectorAll('.profileimage').forEach(profileimage => {
            let user = profileimage.dataset.user;

            function assign_image(imageURL)
            {
                document.querySelectorAll(`.${user}`).forEach(e => {
                    e.src = imageURL;
                });
            }

            fetch(`profile/image/${user}`)
            .then(response => response.json())
            .then(image => {
                let imageURL;
                imageURL = image.image;
                assign_image(imageURL);
            })
            .catch(function() {
                console.log("Could not fetch profile image");
            });
            
        });
    }

    document.addEventListener('DOMContentLoaded', function() {
        //funtion to fetch profile image for each post and add it to the media object
        post_profile_image();
    });

</script>

<img class="img-thumbnail mr-3 profileimage {{ post.post_user }}" data-user='{{ post.post_user }}' src="" alt="profile image">

文件夹结构

├───media
│   ├───1
│   ├───2
│   ├───29
│   ├───3
│   ├───34
│   ├───5
│   ├───7
│   
├───network
│   ├───migrations
│   │   └───__pycache__
│   ├───static
│   │   └───network
│   ├───templates
│   │   └───network
│   └───__pycache__
└───project4
    └───__pycache__

我从管理员上传的个人资料图片进入媒体文件夹中每个编号的文件夹(用户 ID)。

【问题讨论】:

    标签: python django imagefield


    【解决方案1】:

    我能够通过更正视图来解决此问题。

    profile = UserProfile.objects.get(profile_user=user)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-12
      • 2013-11-26
      • 1970-01-01
      • 2020-12-21
      • 1970-01-01
      相关资源
      最近更新 更多