【问题标题】:How to add profile picture on django如何在 django 上添加个人资料图片
【发布时间】:2020-09-18 11:16:24
【问题描述】:

我一直在尝试向用户添加个人资料图片,但该文件似乎“未知”,所以我认为 profile.html 上有错误,但我不知道如何解决。

views.py

    def profile(request, username=None):
      if username:
        post_owner = get_object_or_404(User, username=username)
        user_posts = Profile.objects.filter(user_id=post_owner)
      else:
        post_owner = request.user
        user_posts = Profile.objects.filter(user=request.user)
      args1 = {
        'post_owner': post_owner,
        'user_posts': user_posts,
      }
      return render(request, 'profile.html', args1)

models.py

    class Profile(models.Model):
      user = models.OneToOneField(User, on_delete=models.CASCADE)
      profile_pic = models.ImageField(upload_to='profile_pics', null=True, blank="True", default="default.png")

      def __str__(self):
        return f'{self.user.username} Profile'

profile.hmtl

    <h2 class="account-heading">{{ post_owner.username }}</h2>
    <img class="account-img" src="{{ user.profile.profile_pics.url }}" style="max-width: 300px; max-height: 300px;margin-left: 15px;margin-right:15px;">
    <h2 class="account-heading">{{ post_owner.first_name }}</h2>

顺便说一句,我已经安装了枕头,但我会添加 settings.py 和 urls.y 以便你看到它:)

views.py

    MEDIA_URL = '/media/'
    MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

urls.py

   from django.conf import settings
   from django.conf.urls.static import static

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

【问题讨论】:

  • 我不知道这是否是您的问题中的拼写错误,但您在 views.py 中设置了 MEDIA_URL 但在您的 urls.py 中您引用 settings.MEDIA_URL 而不是在中声明的 MEDIA_URL你的意见.py.
  • @RedCricket 你什么意思?我想导入一些东西吗?
  • 不,我没有说您缺少导入。我说你没有使用你在views.py中声明的MEDIA_URL。为什么不在 settings.py 文件中设置MEDIA_URL

标签: html django django-models django-views django-templates


【解决方案1】:

您将字段定义为profile_pic,但您尝试在您的html 文件中访问profile_pics。像这样更改img 元素的src 属性:

src="{{ user.profile.profile_pic.url }}"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-20
    • 1970-01-01
    • 1970-01-01
    • 2011-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多