django - 等效于get_or_create用于添加用户

标签 django

有没有一种比以下模式更简单的添加用户的方法?

    try:
        new_user = User.objects.create_user(username, email, password)
    except IntegrityError:
        messages.info(request, "This user already exists.")
    else:
        new_user.first_name = first_name
        # continue with other things

最佳答案

我不这么认为。但是您可以代理Django用户:

class MyUser(User):
    class Meta:
        proxy = True

    def get_or_create(self, username, email, password, *args, **kwargs):
        try:
            new_user = User.objects.create_user(username, email, password)
        except IntegrityError:
            return User.objects.get(username=username, email=email)
        else:
            new_user.first_name = kwargs['first_name'] # or what you want
            ...etc...

        return new_user

关于django - 等效于get_or_create用于添加用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7511391/

相关文章:

javascript - Django 复选框全选

python - Django:form_valid 和模型验证

linux - 550 次浏览.py : Permission denied

python - GridFS (MongoDB) 的自定义存储系统?

python - LoginRequiredMixin 的反面是什么,如何拒绝登录用户的访问?

python - 在多个模型上使用单个多对多关系表而不是多对多和外键字段?

python - Buildout 是否可以覆盖包含其自身依赖项的应用程序的依赖项?

django - 一条特定路由的 uwsgi 段错误

python - createsuperuser 命令中的 django+heroku+postgres 错误,它给出错误 "psycopg2.errors.UndefinedTable: relation "users_profile“不存在”

python - CommandError: Elasticsearch 中未命名任何模型或应用