为用户添加图像/头像字段
我希望我网站上的每个用户的个人资料中都有一张图片。我不需要任何缩略图或类似的东西,只需要每个用户的图片。越简单越好。问题是我不知道如何将此类字段插入我的用户个人资料中。有什么建议吗?
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要创建一个具有干净方法的表单来验证您正在寻找的属性:
You need to make a form that has a clean method that validates the properties you're looking for:
要将 UserProfile 模型连接到您的 User 模型,请确保您按照本教程中的详细说明扩展您的 User 模型: http://www.b-list.org/weblog/2006/jun/06/django-tips-extending-user-model/
这将允许您访问用户的 UserProfile 属性,包括头像,使用 user.get_profile().avatar。 (请注意模板中不同的语法,请参阅下文了解如何在模板中显示头像。)
您可以在 UserProfile 模型中使用图像字段作为头像:
这与 FileField 完全相同,但特定于图像并验证上传的对象是有效的图像。要限制文件大小,您可以使用@pastylegs 此处给出的答案:
文件上传时的最大图像大小
然后,假设您的用户配置文件模型称为 UserProfile,您可以按如下方式访问模板中的头像:
有关图像字段的更多信息:
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:
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:
More about the image field here:
https://docs.djangoproject.com/en/dev/ref/models/fields/#imagefield
假设您使用标准
contrib.auth
,您可以将模型指定为 '用户个人资料'模型,通过AUTH_PROFILE_MODULE
设置。然后,您可以使用它将任何您想要的附加信息附加到User
对象,例如Assuming you're using standard
contrib.auth
, you can designate a model as an 'user profile' model, viaAUTH_PROFILE_MODULE
setting. You can then use it to attach any additional information you want to theUser
objects, e.g.