我需要帮助修复下面的内容,问题是它会保存两次,并在插入UserProfile表时找到重复值。现在已经挣扎了很长时间。
错误消息:django.db.utils.IntegrityError:重复键值违反唯一约束“user_profile_user_id_key” DETAIL:Key(user_id)=(71)已经存在。
models.py
class UserProfile(models.Model):
user = models.OneToOneField(User, related_name='user')
phone = models.CharField(max_length=20, blank=True, default='')
def __unicode__(self):
return self.user.username
class Meta:
db_table = "UserProfile"
forms.py
class ProfileForm(forms.ModelForm):
phone = forms.CharField(required=True)
class Meta:
model = UserProfile
fields = ('phone')
class MyRegistrationForm(UserCreationForm):
first_name = forms.CharField(required=True)
last_name = forms.CharField(required=True)
class Meta:
model = User
fields = ('first_name', 'last_name', 'username', 'email', 'password1', 'password2')
views.py
def register_user(request):
if request.user.is_authenticated():
return HttpResponseRedirect('/user/')
else:
if request.method == 'POST':
myregistrationform = MyRegistrationForm(request.POST, prefix='registration')
userprofileform = ProfileForm(request.POST, prefix='profile')
if myregistrationform.is_valid() and userprofileform.is_valid():
registration = myregistrationform.save()
profile = userprofileform.save(commit=False)
profile.user = registration
profile.save()
return HttpResponseRedirect('/accounts/registration_complete')
else:
myregistrationform = MyRegistrationForm()
userprofileform = ProfileForm()
return render(request,
'register.html',
{'myregistrationform': myregistrationform, 'userprofileform': userprofileform})
堆栈追踪:
[08/Sep/2016 07:36:09] "GET /register_user/ HTTP/1.1" 200 1521
[08/Sep/2016 07:36:28] "POST /register_user/register/ HTTP/1.1" 200 2247
Internal Server Error: /register_user/register/register/
Traceback (most recent call last):
File "/home/Documents/virtual_environment/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
psycopg2.IntegrityError: duplicate key value violates unique constraint "user_profile_user_id_key"
DETAIL: Key (user_id)=(71) already exists.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/Documents/virtual_environment/lib/python3.4/site-packages/django/core/handlers/exception.py", line 39, in inner
response = get_response(request)
File "/home/Documents/virtual_environment/lib/python3.4/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/Documents/virtual_environment/lib/python3.4/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/Documents/virtual_environment/archive_project/portal_app/views.py", line 240, in register_user
profile.save()
File "/home/Documents/virtual_environment/lib/python3.4/site-packages/django/db/models/base.py", line 796, in save
force_update=force_update, update_fields=update_fields)
File "/home/Documents/virtual_environment/lib/python3.4/site-packages/django/db/models/base.py", line 824, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/home/Documents/virtual_environment/lib/python3.4/site-packages/django/db/models/base.py", line 908, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/home/Documents/virtual_environment/lib/python3.4/site-packages/django/db/models/base.py", line 947, in _do_insert
using=using, raw=raw)
File "/home/Documents/virtual_environment/lib/python3.4/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/Documents/virtual_environment/lib/python3.4/site-packages/django/db/models/query.py", line 1043, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "/home/Documents/virtual_environment/lib/python3.4/site-packages/django/db/models/sql/compiler.py", line 1054, in execute_sql
cursor.execute(sql, params)
File "/home/Documents/virtual_environment/lib/python3.4/site-packages/django/db/backends/utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/home/Documents/virtual_environment/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/home/Documents/virtual_environment/lib/python3.4/site-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/home/Documents/virtual_environment/lib/python3.4/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/home/Documents/virtual_environment/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
django.db.utils.IntegrityError: duplicate key value violates unique constraint "user_profile_user_id_key"
DETAIL: Key (user_id)=(71) already exists.