为用户添加图像/头像字段

发布于 2024-11-15 23:18:49 字数 98 浏览 7 评论 0原文

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

软甜啾 2024-11-22 23:18:49

您需要创建一个具有干净方法的表单来验证您正在寻找的属性:

#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

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
挖鼻大婶 2024-11-22 23:18:49

要将 UserProfile 模型连接到您的 User 模型,请确保您按照本教程中的详细说明扩展您的 User 模型: http://www.b-list.org/weblog/2006/jun/06/django-tips-extending-user-model/

这将允许您访问用户的 UserProfile 属性,包括头像,使用 user.get_profile().avatar。 (请注意模板中不同的语法,请参阅下文了解如何在模板中显示头像。)

您可以在 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 /模型/字段/#imagefield

To connect the UserProfile model to your User model make sure you are extending your User model as fully explained in this tutorial: http://www.b-list.org/weblog/2006/jun/06/django-tips-extending-user-model/

This will allow you to access UserProfile attributes for your User, including the avatar, using user.get_profile().avatar. (Note the syntax in different in your template, see below for how to display the avatar in your template.)

You can use an image field in your UserProfile model for the avatar:

#upload at specific location
avatar = models.ImageField(upload_to='images')

This works exactly like a FileField but is specific for images and validates that the uploaded object is a valid image. To limit the file size you can use the answer given here by @pastylegs:
Max image size on file upload

Then, assuming your userprofile model is called UserProfile, you access the avatar in your template as follows:

<img src=path/to/images/{{ user.get_profile.avatar }}">

More about the image field here:
https://docs.djangoproject.com/en/dev/ref/models/fields/#imagefield

风追烟花雨 2024-11-22 23:18:49

假设您使用标准 contrib.auth,您可以将模型指定为 '用户个人资料'模型,通过 AUTH_PROFILE_MODULE 设置。然后,您可以使用它将任何您想要的附加信息附加到 User 对象,例如

from django.contrib.auth.models import User

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

Assuming you're using standard contrib.auth, you can designate a model as an 'user profile' model, via AUTH_PROFILE_MODULE setting. You can then use it to attach any additional information you want to the User objects, e.g.

from django.contrib.auth.models import User

class UserProfile(models.Model):
    user   = models.OneToOneField(User)
    avatar = models.ImageField() # or whatever
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文