0

我坚持同样的任务。我有一个更改用户注册数据(用户名、职业等)的视图,但我不知道:如何更改用户头像(下载和设置)

查看编辑用户数据:

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

任何想法?请各位大侠帮忙。

4

1 回答 1

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

于 2013-06-28T20:26:27.393 回答