将图像/头像字段添加到django中的用户 [英] Add image/avatar field to users in django

查看:166
本文介绍了将图像/头像字段添加到django中的用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我网站上的每个用户的个人资料中都有一张图片.我不需要任何缩略图或类似的东西,只需为每个用户提供图片即可.越简单越好.问题是我不知道如何将这种类型的字段插入我的用户个人资料.有什么建议吗?

I want that each user in my website will have an image in his profile. I don't need any thumbnails or something like that, just picture for each user. The simpler the better. The problem is I don't know how to insert this type of field to my user profile. Any suggestions?

推荐答案

您需要制作一个表单,该表单具有用于验证您要查找的属性的干净方法:

You need to make a form that has a clean method that validates the properties you're looking for:

#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

希望对您有帮助.

这篇关于将图像/头像字段添加到django中的用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆