我有一个名为 ProfilePicture 的 Django 模型,我已将其从 Profile_Picture 重命名为 ProfilePicture,以便它符合 Python 命名约定。现在,我正在像这样访问它
request.user.profilepicture
。我想知道是否可以更改它以便我可以像这样访问它:request.user.profile_picture
或者是否有更好的做事方式因为request.user.profilepicture
看起来很奇怪
我已经看到这里建议的答案:Referencing multiword model object in Django
但是,我已经尝试过
request.user.profilepicture_set.all()
,它只是说该属性不存在。就算是,还是觉得有点不对
如果你只需要保留用户的profile_picture,则不需要像你一样创建额外的Model。您可以使用 Django 用户模型和 AbstractUser 它允许您添加新的自定义字段。
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
profile_picture = models.ImageField(blank=True, null=True, upload_to='images')
然后你就可以访问图像了
有关更多详细信息,请查看以下链接:
https://docs.djangoproject.com/en/4.1/topics/auth/customizing/#auth-custom-user
我想我找到了答案,我已经测试过它似乎按照我想要的方式工作所以我要把它留在这里以防它帮助其他人。
class ProfilePicture(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile_picture")
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
def __str__(self):
return f'{self.user.username} Profile Picture'
通过将
related_name="profile_picture"
添加到上面的 OneToOneField
,我可以使用 user.request.profile_picture
而不是默认的 user.request.profilepicture