在django中向用户添加图片/头像字段

|| 我希望我网站上的每个用户的个人资料中都可以有一张图片。我不需要任何缩略图或类似的东西,只需为每个用户提供图片即可。越简单越好。问题是我不知道如何将这种类型的字段插入我的用户个人资料。有什么建议么?     
已邀请:
        您需要制作一种具有干净方法的表单,该方法可以验证您要查找的属性:
#models.py
from django.contrib.auth.models import User

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


#forms.py
from django import forms
from django.core.files.images import get_image_dimensions

from my_app.models import UserProfile


class UserProfileForm(forms.ModelForm):
    class Meta:
        model = UserProfile

    def clean_avatar(self):
        avatar = self.cleaned_data[\'avatar\']

        try:
            w, h = get_image_dimensions(avatar)

            #validate dimensions
            max_width = max_height = 100
            if w > max_width or h > max_height:
                raise forms.ValidationError(
                    u\'Please use an image that is \'
                     \'%s x %s pixels or smaller.\' % (max_width, max_height))

            #validate content type
            main, sub = avatar.content_type.split(\'/\')
            if not (main == \'image\' and sub in [\'jpeg\', \'pjpeg\', \'gif\', \'png\']):
                raise forms.ValidationError(u\'Please use a JPEG, \'
                    \'GIF or PNG image.\')

            #validate file size
            if len(avatar) > (20 * 1024):
                raise forms.ValidationError(
                    u\'Avatar file size may not exceed 20k.\')

        except AttributeError:
            \"\"\"
            Handles case when we are updating the user profile
            and do not supply a new avatar
            \"\"\"
            pass

        return avatar
希望对您有所帮助。     
        要将UserProfile模型连接到User模型,请确保按照本教程中的完整说明扩展User模型:http://www.b-list.org/weblog/2006/jun/06/django-tips-extending-用户模型/ 这将允许您使用user.get_profile()。avatar访问用户的UserProfile属性,包括头像。 (请注意,模板中的语法不同,请参见下文,了解如何在模板中显示头像。) 您可以在UserProfile模型中为头像使用图像字段:
#upload at specific location
avatar = models.ImageField(upload_to=\'images\')
这与FileField完全一样,但特定于图像,并验证上载的对象是否为有效图像。要限制文件大小,您可以使用@pastylegs在此处给出的答案: 文件上传时的最大图片大小 然后,假设您的用户配置文件模型称为UserProfile,您可以如下访问模板中的化身:
<img src=path/to/images/{{ user.get_profile.avatar }}\">
有关图像字段的更多信息,请参见: https://docs.djangoproject.com/en/dev/ref/models/fields/#imagefield     
        假设您使用的是标准
contrib.auth
,则可以通过
AUTH_PROFILE_MODULE
设置将一个模型指定为“用户个人资料”模型。然后,您可以使用它将所需的任何其他信息附加到“ 5”对象,例如
from django.contrib.auth.models import User

class UserProfile(models.Model):
    user   = models.OneToOneField(User)
    avatar = models.ImageField() # or whatever
    

要回复问题请先登录注册