Duplicate key value violates unique constraint while saving ModelForm

徘徊边缘 提交于 2019-12-14 04:16:53

问题


My views.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})

my models.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  

my forms.py

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

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

While submitting the POST request, it gives me:

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.

I have even tried changing the database, running manage.py flush but still no luck. Please give me leads.

These are the Postgres tables:

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

回答1:


The idea of having a separate table users_userprofile is probably to allow multiple entries for a single user.

(Else, if there can only be a single attribute rewardpoints per user, you would just add the column to the table auth_user and drop the table users_userprofile.)

The actual implementation contradicts this idea. You have a UNIQUE constraint on users_userprofile.user_id, which does not make sense:

"users_userprofile_user_id_key" UNIQUE CONSTRAINT, btree (user_id)

It causes the error and should probably be removed.



来源:https://stackoverflow.com/questions/28615208/duplicate-key-value-violates-unique-constraint-while-saving-modelform

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!