更改用户头像

时间:2013-06-28 19:37:23

标签: python django avatar

我陷入了同样的困境。我有一个视图用于更改用户注册数据(用户名,专业等),但我不知道:如何更改用户头像(下载和设置)

查看编辑用户数据:

def edit_personal_information(request):
if request.method == "POST" :
    username = request.POST["username"]
    profession = request.POST["search_specialist"]
    coordinate_x = request.POST["coordinate_x"]
    coordinate_y = request.POST["coordinate_y"]
    profile_vkontakte = request.POST["profile_vkontakte"]
    request.user.username = username
    request.user.profession = profession
    request.user.coordinate_x = coordinate_x
    request.user.coordinate_y = coordinate_y
    request.user.profile_vkontakte = profile_vkontakte
    request.user.save()
    return redirect("/personal_information")
c = {}
c.update(csrf(request))
return render(request, "edit_personal_information.html"

用户表单

class User(AbstractBaseUser):
email = models.EmailField(
    verbose_name='Email address',
    max_length=45,
    unique=True,
    db_index=True,
)
username = models.TextField(verbose_name='Nick', max_length=15, unique=True)
profession = models.TextField(verbose_name='Profession', max_length=15)
avatar = models.FileField(upload_to=get_upload_file_name, blank=True, null=True)
profile_vkontakte = models.TextField(verbose_name='Profile in vkontakte', max_length=10, null=True)
coordinate_x = models.FloatField(verbose_name='X', null=True)
coordinate_y = models.FloatField(verbose_name='Y', null=True)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)

objects = UserManager()

USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email']

def get_full_name(self):
    return '%s %s' % (self.first_name, self.last_name,)

def get_short_name(self):
    return self.username

def __unicode__(self):
    return self.email

def has_perm(self, perm, obj=None):
    return True

def has_module_perms(self, app_label):
    return True

@property
def is_staff(self):
    return self.is_admin

有什么想法吗?伙计们,帮忙。

1 个答案:

答案 0 :(得分:0)

在您的模板中,将其添加到表单标记

enctype="multipart/form-data"

创建一个名为user_profile的新模型

from django.contrib.auth.models import User

class user_profile(models.Model):
    user   = models.OneToOneField(User)
    avatar = models.ImageField()

现在在request.user.save()

之后将用户的图像保存在此字段中
from django.core.files import File
new_user_profile = user_profile()
new_user_profile.user = request.user
new_user_profile.avatar.save(avatars_file_name,File(handle_upload_file(request.FILES['your_file_input_name_in_template_form'])


from django.core.files.temp import NamedTemporaryFile
def handle_upload_file(f):
        img_temp = NamedTemporaryFile()
        for chunk in f.chunks():
                img_temp.write(chunk)
        img_temp.flush()
        return img_temp

您还可以参考此问题,了解另一种方法和想法Add image/avatar to users in django