简体   繁体   English

如何在 django 上添加头像

[英]How to add profile picture on django

I have been trying to add a profile picture to users but the file seems to be "unknown" so I think the error is on the profile.html but I dont know how to fix it.我一直在尝试向用户添加个人资料图片,但文件似乎是“未知的”,所以我认为错误出现在 profile.html 但我不知道如何修复它。

views.py视图.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模型.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配置文件.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>

btw I have pillow installed, but I will add the settings.py and urls.y so that you van see it:)顺便说一句,我已经安装了枕头,但我会添加 settings.py 和 urls.y 以便你看到它:)

views.py视图.py

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

urls.py网址.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)

You define field as profile_pic but you try to reach profile_pics in your html file.您将字段定义为profile_pic ,但您尝试在 html 文件中访问profile_pics Change the src attribute of img element like this:像这样更改img元素的src属性:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM