我正在编写需要处理用户和配置文件的简单网站。最初的想法是在用户处理中使用 django 的构建,但是用户模型太窄并且不包含我需要的字段。该文档提到了用户配置文件,但用户配置文件部分已从覆盖 django 1.0 的 djangobook 中删除(理想情况下,该解决方案应适用于 django 1.2),并且互联网上充满了不同的解决方案,并没有使选择更容易(如用户模型继承,用户配置文件和 django 信号等)。
我想知道如何以良好、现代、快速和安全的方式编写此代码。我应该尝试扩展 django 内置用户模型,还是应该创建我自己的用户模型足够宽以保留我需要的所有信息?您可能会在下面找到工作解决方案的一些规范和期望:
- 用户应该能够注册和验证
- 每个用户都应该有个人资料(或包含所有必填字段的模型)
- 用户不需要 django 内置管理面板,但他们需要通过简单的网络表单编辑他们的配置文件/模型
请让我知道您如何解决应用程序中的这些问题,以及当前使用 django 处理用户的最佳方式是什么。非常感谢任何指向文章/博客或代码示例的链接!
最佳答案
users should be able to register and authenticate
django.contrib.auth
就是你要的模块。请务必查看 custom login forms. 的文档
every user should have profile (or model with all required fields)
如其他人所述,您需要设置 settings.AUTH_PROFILE_MODULE
。
有关设置用户配置文件模型的信息可用于 the latest version , 1.1 , 和 1.0 .它没有被丢弃。
users dont need django builtin admin panel, but they need to edit their profiles/models via simple web form
您可以像创建任何其他应用程序一样创建表单和 View ;也许制作一个“用户控制面板”应用程序来处理这些事情。然后,您的 View 将与 django.contrib.auth.models.User
和 django.contrib.auth.models.Group
模型交互。您可以将其设置为执行您需要的任何操作。
编辑:以答案的形式回答您的问题(寻呼 Alex Trebek)...
The second version of djangobook, covering django 1.0 (that is way closer to 1.2 than 0.96) no longer has that information anywhere, what makes me highly confused - has anything changed? Is there other, better, more secure way to handle users and their profiles? Therefore this question asked.
我不会推荐 djangobook 作为引用;这个话题已经过时了。存在用户配置文件,我在我的 Django 1.1.1 站点中使用它们;我什至从 NIS 填充它们。
请使用我上面提供的链接。他们直接转到实际的 Django 文档并且是权威的。
By the way, I forgot to ask, if the way you all refer to (that is AUTH_PROFILE_MODULE) will create automatically upon registration
在文档中回答。
and require the profile to exist upon any action (user withoud existing, filled profile should not exists, this is why I was thinking about extending User model somehow)?
如果调用 User.get_profile()
,则配置文件需要存在。
Will it get updated as well (people are mentioning 'signals' on various blogs related to this subject)?
它与任何其他模型一样:只有在您更改字段并调用 save()
时才会更新。
signal部分是如何 Hook 一个函数来为新用户创建配置文件:
from django.db.models.signals import post_save
from django.contrib.auth import User
from myUserProfileApp import UserProfile
def make_user_profile(sender, **kwargs):
if 'created' not in kwargs or not kwargs['created']:
return
# Assumes that the `ForeignKey(User)` field in "UserProfile" is named "user".
profile = UserProfile(user=kwargs["instance"])
# Set anything else you need to in the profile, then...
profile.save()
post_save.connect(make_user_profile, sender=User, weak=False)
这只会为新用户创建新的配置文件。现有用户需要手动添加配置文件:
$ ./manage.py shell
>>> from django.contrib.auth import User
>>> from myUserProfileApp import UserProfile
>>> for u in User.objects.all():
... UserProfile(user=u).save() # Add other params as needed.
...
如果您有一些用户有个人资料而一些没有,您需要做更多的工作:
>>> for u in User.objects.all():
... try:
... UserProfile(user=u).save() # Add other params as needed.
... except:
... pass
关于python - Django - 如何以最佳方式编写用户和配置文件处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2654689/