Django无法在UserProfile中创建新对象

时间:2015-06-24 15:55:13

标签: python django python-3.x django-models django-views

我有如下的UserProfile:

def get_image_path(instance, filename):
    formats = str(instance.id) + 'moolak' + '.' + filename.split('.')[-1]
    path = os.path.join(os.path.dirname(os.path.dirname(__file__)), str(instance.id)+'/avatar', formats)
    return path


class UserProfile(models.Model):
    user = models.OneToOneField(User)
    avatar = models.ImageField(blank=True, upload_to=get_image_path)
    age = models.IntegerField(default=4, blank=True, validators=[MinValueValidator(3), MaxValueValidator(99)])
    birth_day = models.DateField(default=date(2015, 1, 1))
    location = CountryField()
    gender = models.CharField(max_length=1, choices=SEX, default='N')
    about_me = models.CharField(max_length=100, blank=True)
    call_no = models.PositiveIntegerField(default=0)
    login_count = models.PositiveIntegerField(default=0)

    def save(self, *args, **kwargs):
        if self.id is not None:
            this = UserProfile.objects.get(pk=self.id)
            if this.avatar != self.avatar:
                this.avatar.delete(save=True)
            super(UserProfile, self).save(*args, **kwargs)

    def __str__(self):
        return "%s" % self.user

我的Setting.py如下所示:

STATIC_URL = '/static/'
AUTH_PROFILE_MODULE = 'profiles.UserProfile'
TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]
MEDIA_ROOT = 'media/'
MEDIA_URL = '/media/'

当我尝试通过create或其他语法创建对象时。 我给出了以下错误:

No UserProfile matches the given query.

但是,当我从UserProfile及其相应的代码中删除avatar时,它可以正常工作。 我认为Django无法保存图像!你能帮助我吗,我是新手。 我想将图像保存到:

 `current-project-directory/static/media/images/avatar`

0 个答案:

没有答案