根据用户模型的 post_save 信号创建用户配置文件

User Profile Creation on User model's post_save signal

我有 UserProfile 模型,只要使用 post_save 信号创建用户,我就会实例化该模型,除用户配置文件中的 ImageField 外,一切正常。我正在使用 django-allauth 进行注册和登录。当我尝试访问任何用户的个人资料页面时,控制台重复打印:

[28/Dec/2016 12:22:06] "GET /media/C%3A/Users/shagu/Desktop/zorion-develop/project_1
/media/profile/images/Users/shagu/Desktop/zorion-develop/project_1/media/profile/images/...

并说到此结束

    ../zorion-develop/project_1/media/profile/images/nobody.jpg HTTP/1.1" 302 0
[28/Dec/2016 12:24:26] code 414, message Request-URI Too Long
[28/Dec/2016 12:24:26] "" 414 -

配置文件模型如下:

class UserProfile(models.Model):
    user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE)
    image = models.ImageField(width_field="width_field",
                              height_field="height_field",
                              upload_to=os.path.join(settings.MEDIA_ROOT,'media', 'profile','images'),
                              default = os.path.join(settings.MEDIA_ROOT,'media', 'profile','images', 'nobody.jpg'),
                              )
    height_field = models.IntegerField(default=0)
    width_field = models.IntegerField(default=0)
    age = models.IntegerField(null=True, blank=True)
    gender = models.CharField(
        choices=(
            ('M', 'male'),
            ('F', 'female'),
        ),
        default='M', max_length=1)
    profile_confirmed = models.BooleanField(default=False)

媒体相关设置如下:

MEDIA_ROOT = os.path.join(os.path.dirname(PROJECT_ROOT))
MEDIA_URL = "/media/"

这就是我尝试访问模板中的图像的方式:

<div align="center"><img alt="User Pic" src="{{ user.userprofile.image.url }}" id="profile-image1" class="img-circle img-responsive">

我对 django 有点陌生。请让我知道我哪里搞砸了。

完全理解和解决您的问题所需的信息很少,但我可以给您一个可能会解决问题的提示。

首先,你的 MEDIA_ROOT 在当前状态下指向你的项目之外,因为 PROJECT_ROOT 可能类似于 '/home/user/myproject' 而 MEDIA_ROOT 将是'/home/user'。不管怎样,如果你真的想要它,那也没关系。但实际上我会把它改成:

MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media')

其次,在你的

中使用绝对路径
upload_to=os.path.join(settings.MEDIA_ROOT,'media', 'profile','images')

实际上不是一个好习惯。您应该使用相对路径,Django 实际上会相对于 MEDIA_ROOT 和 MEDIA_URL 构建正确的路径(以及将来的 link)。像这样:

upload_to=os.path.join('', 'profile','images')

在你做了假定的修复后,为你的图像字段上传一个新的 file/image,因为我想 Django 已经以错误的方式将 link 存储在你的数据库中,强烈建议进行干净测试。