保存 ModelForm 时重复的键值违反唯一约束

2024-01-03

我的观点.py

class UserProfileFormView(View):
    def post(self, request, *args, **kwargs):
        userform = UserForm(request.POST, prefix='users')
        userprofileform = UserProfileForm(request.POST, prefix='userprofiles')
        if userform.is_valid() and userprofileform.is_valid():
            new_user = userform.save()
            new_userprofile = userprofileform.save(commit=False)
            new_userprofile.user = new_user  
            new_userprofile.save() #### Error is here
            return HttpResponseRedirect(reverse('users:welcome'))
        else:
            userform = UserForm(prefix='users')
            userprofileform = UserProfileForm(prefix='userprofiles')
            return render(request, 'users/signup.html', {'user_form': userform, 'userprofile_form': userprofileform})
    def get(self, request, *args, **kwargs):
        userform = UserForm(prefix='users')
        userprofileform = UserProfileForm(prefix='userprofiles')    
        return render(request, 'users/signup.html', {'user_form': userform, 'userprofile_form': userprofileform})

我的模型.py

class UserProfile(models.Model): 
    user = models.OneToOneField(User, verbose_name="user details")
    rewardpoints = models.IntegerField("rewardpoints", default=0) 

    def __str__(self):  
          return "%s's profile" % self.user.username  

我的表单.py

class UserProfileForm(ModelForm):
    class Meta:
        model = UserProfile
        fields = ['rewardpoints']

class UserForm(ModelForm):
    class Meta:
        model = User
        fields = ['username', 'password']

在提交的同时POST请求,它给了我:

duplicate key value violates unique constraint "users_userprofile_user_id_key"
DETAIL:  Key (user_id)=(1) already exists.

Django-1.7、PostgreSQL 9.3.6。

我什至尝试更改数据库,运行manage.py flush但仍然没有运气。请给我线索。

这些是 Postgres 表:

auth_user

    Column    |           Type           |                       Modifiers                        
--------------+--------------------------+--------------------------------------------------------
 id           | integer                  | not null default nextval('auth_user_id_seq'::regclass)
 password     | character varying(128)   | not null
 last_login   | timestamp with time zone | not null
 is_superuser | boolean                  | not null
 username     | character varying(30)    | not null
 first_name   | character varying(30)    | not null
 last_name    | character varying(30)    | not null
 email        | character varying(75)    | not null
 is_staff     | boolean                  | not null
 is_active    | boolean                  | not null
 date_joined  | timestamp with time zone | not null
Indexes:
    "auth_user_pkey" PRIMARY KEY, btree (id)
    "auth_user_username_key" UNIQUE CONSTRAINT, btree (username)
    "auth_user_username_615a2337ed0898d6_like" btree (username varchar_pattern_ops)
Referenced by:
    TABLE "account_emailaddress" CONSTRAINT "account_emailaddress_user_id_43dc87ab5814030c_fk_auth_user_id" FOREIGN KEY (user_id) REFERENCES auth_user(id) DEFERRABLE INITIALLY DEFERRED
    TABLE "auth_user_groups" CONSTRAINT "auth_user_groups_user_id_365abed9418f0260_fk_auth_user_id" FOREIGN KEY (user_id) REFERENCES auth_user(id) DEFERRABLE INITIALLY DEFERRED
    TABLE "auth_user_user_permissions" CONSTRAINT "auth_user_user_permiss_user_id_50dbc406b985ecc5_fk_auth_user_id" FOREIGN KEY (user_id) REFERENCES auth_user(id) DEFERRABLE INITIALLY DEFERRED
    TABLE "authtoken_token" CONSTRAINT "authtoken_token_user_id_1496385360418da0_fk_auth_user_id" FOREIGN KEY (user_id) REFERENCES auth_user(id) DEFERRABLE INITIALLY DEFERRED
    TABLE "django_admin_log" CONSTRAINT "django_admin_log_user_id_1f9a3ebc14adbded_fk_auth_user_id" FOREIGN KEY (user_id) REFERENCES auth_user(id) DEFERRABLE INITIALLY DEFERRED
    TABLE "users_userprofile" CONSTRAINT "users_userprofile_user_id_35e6cb6eb864c8ec_fk_auth_user_id" FOREIGN KEY (user_id) REFERENCES auth_user(id) DEFERRABLE INITIALLY DEFERRED

users_userprofile

  Column      |  Type   |                           Modifiers                            
--------------+---------+----------------------------------------------------------------
 id           | integer | not null default nextval('users_userprofile_id_seq'::regclass)
 rewardpoints | integer | not null
 user_id      | integer | not null
Indexes:
    "users_userprofile_pkey" PRIMARY KEY, btree (id)
    "users_userprofile_user_id_key" UNIQUE CONSTRAINT, btree (user_id)
Foreign-key constraints:
    "users_userprofile_user_id_35e6cb6eb864c8ec_fk_auth_user_id" FOREIGN KEY (user_id) REFERENCES auth_user(id) DEFERRABLE INITIALLY DEFERRED

有一个单独的表的想法users_userprofile可能是允许单个用户多个条目。

(否则,如果只能有一个属性rewardpoints对于每个用户,您只需将列添加到表中auth_user并放下桌子users_userprofile.)

实际的实施与这个想法相矛盾。你有一个UNIQUE约束于users_userprofile.user_id,这没有意义:

"users_userprofile_user_id_key" UNIQUE CONSTRAINT, btree (user_id)

它会导致错误,可能应该被删除。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

保存 ModelForm 时重复的键值违反唯一约束 的相关文章

  • python:发送邮件,在“with”块内时失败

    我想知道为什么这段代码 test smtplib SMTP smtp gmail com 587 test ehlo test starttls test ehlo test login address passw test sendmai
  • @monthly cron 作业不可靠

    我们的客户希望我们每月创建一份报告 过去 我们使用 monthly cron 作业来完成此任务 但这并不可靠 服务器可能会在这一分钟内宕机 Cron 不会重新运行这些作业 如果服务器已启动 此时数据库可能无法访问 如果服务器已启动且数据库已
  • Django:通过外键将两个表连接到第三个表?

    我有三个型号 class A Model class B Model id IntegerField a ForeignKey A class C Model id IntegerField a ForeignKey A 我想要得到 B i
  • Django 与 mod_wsgi 在 apache - 500 错误:Authtype 未设置?

    尝试在 Dreamhost 上部署我的第一个 django 站点 我的这个工作正常 然后我不确定我做了什么让它停止工作 这是错误消息 crit client 74 72 99 26 configuration error couldn t
  • 使用 PyQt5 拖放 QLabels

    我正在尝试使用 PyQt5 将 Qlabel 拖放到另一个 Qlabel 上 from PyQt5 QtWidgets import QApplication QWidget QToolTip QPushButton QMessageBox
  • 将 Django OAuth2 提供程序与 JupyterHub 结合使用

    我正在尝试运行与 JupyterHub 服务器配对的 Django Web 应用程序 用户通过 Web 应用程序输入 然后在登录后获得对笔记本服务器的访问权限 为了促进这一点 我尝试使用OAuth2 其中 Django 提供身份验证 Jup
  • 使用 Django Admin 上传文件

    我希望能够使用 Django 管理界面上传 PDF 文件 并将这些文件反映在我网站的页面中 这是可能吗 如果是这样 我该怎么做 否则 管理员用户私下上传稍后将在网站中显示的文件的解决方法是什么 我从 Django 文档中得到的信息文件上传
  • 在上下文中模拟计时,以使用 auto_now_add=True 的字段 DateTimeField 创建模型

    我想模拟时间以便能够set特定时间到某个类型的字段DateTimeField with auto now add True在我的测试期间 例如 class MyModel created at models DateTimeField au
  • ZeroMQ 在 python 多处理类/对象解决方案中挂起

    我正在尝试将 Python pyzmq 中的 ZeroMQ 与多处理一起使用 作为一个最小的 不是 工作示例 我有一个服务器类和一个客户端类 它们都继承自multiprocessing Process 客户端作为子进程应向服务器子进程发送消
  • 如何隐藏 django-admin 中的某些字段?

    class Book models Model title models CharField null True type models CharField author models CharField 我在 models py 中有一个
  • 如何在 NHibernate 中自动生成 ID

    如何让 NHibernate 自动生成表的唯一 ID ID 可以是任意的long值 只要每个值仅使用一次 我当前的映射如下所示
  • 在 Python 3 中动态导入模块的问题

    我遇到的情况是 在我的 Python 3 项目中 在运行时必须包含某些模块 我在用着importlib import module为了这 第二次更新 我确实找到了一种方法来做一些接近我想要的事情 一些额外的代码可能会使我的一些链接稍微偏离一
  • 模块“tensorflow”没有属性“random_uniform”

    我尝试执行一些深度学习应用程序 并收到模块 tensorflow 没有属性 random uniform 错误 在 CPU 上 代码运行良好 但速度非常慢 为了在 GPU 上运行代码 我需要更改一些定义 下面是我的代码 有任何想法吗 def
  • 查找一列中具有相同值而另一列中具有其他值的行?

    我有一个 PostgreSQL 数据库 将用户存储在users他们参与的表格和对话conversation桌子 由于每个用户可以参与多个对话 并且每个对话可以涉及多个用户 因此我有一个conversation user链接表来跟踪哪些用户正
  • django_debug_toolbar 和 Docker

    因此 我让 docker 和 Django 在本地工作 首先从 Dockerfile 构建一个映像 然后使用 Fig 获取 postgres 映像 将其链接到基础映像 然后运行本地服务器 除了 django debug toolbar 之外
  • 对数据框的行进行排序

    我有以下数据框 adjusted RFC df Node Feature Indicator Scaled Class Direction True False 0 0 km lt 0 181 class 4 0 gt 1 NA 125 1
  • 从 Python 中编译的正则表达式中提取命名组正则表达式模式

    我有一个 Python 正则表达式 其中包含多个命名组 但是 如果先前的组已匹配 则可能会错过与一组匹配的模式 因为似乎不允许重叠 举个例子 import re myText sgasgAAAaoasgosaegnsBBBausgisego
  • django 组合对两个不同基本模型的查询

    我有两个不同的查询集 我想将两个查询集合并 q1 tbl nt 123 objects values list id value geometry filter restriction height exclude condition id
  • 测试中的模型 - Django 1.7 问题

    我正在尝试将我的项目移植为使用 Django 1 7 除了一件事之外 一切都很好 测试文件夹内的模型 Django 1 7 新迁移在内部运行 migrate 命令 在运行syncdb之前 这意味着如果模型未包含在迁移中 它将不会填充到数据库
  • 如何在 typeorm 中使用 LEFT JOIN LATERAL?

    我想在 TypeOrm 中使用以下查询 但找不到将其转换为 TypeOrm 的方法 任何帮助表示赞赏 SELECT FROM blocked times bt LEFT JOIN LATERAL SELECT FROM bookings b

随机推荐