我想显示默认头像,但是当我尝试将其保存在数据库文件中时,会使用新名称进行复制。 如果文件已存在,如何防止更改文件名?
我的代码: models.py
class UserAccount(User):
contacts = models.OneToOneField('self', null = True)
isBanned = models.BooleanField(_('ban status'), default = False,
help_text = _("Display is contact banned by user."))
avatar = FileField(upload_to = 'avatars')
objects = UserManager()
views.py
user = UserAccount.objects.get(username = user_login)
user.first_name = request.POST['first_name']
user.last_name = request.POST['last_name']
user.email = request.POST['email']
try:
file = request.FILES['avatar']
fileName = request.FILES['avatar'].name
except:
fileName = 'static/avatars/default.gif'
file = File(open(fileName, 'r'))
user.avatar.save(fileName, file)
user.save()
答案 0 :(得分:0)
解决方案在于我没有保存头像,而只是将FileField路径用于默认头像。
try:
file = request.FILES['avatar']
fileName = request.FILES['avatar'].name
except:
user.avatar = 'avatars/default.gif'
flag = False
if flag:
user.avatar.save(fileName, file)
user.save()