我正在通过onetoone关系和配置文件模型扩展django用户模型。我想在创建用户实例时创建用户的配置文件,以便使用post_save信号。当我创建用户(使用注册视图)时,配置文件是还创建了我想要的空白和空值。但是当我尝试使用该用户登录时,会出现IntegrityError。
views.py
def register(request):
if request.method == 'POST':
user_form = CreatUserForm(request.POST)
if user_form.is_valid():
new_user = user_form.save(commit=False)
new_user.set_password(user_form.cleaned_data['password'])
new_user.save()
return render(request,'accounts/registration_done.html',{'new_user':new_user})
else:
return render(request,'accounts/registration.html', {'user_form':user_form})
else:
user_form = CreatUserForm()
return render(request,'accounts/registration.html',{'user_form':user_form})
@login_required
def edit_profile(request):
if request.method == 'POST':
user_edit_form = UserEditForm(instance=request.user,data=request.POST)
profile_edit_form = ProfileEditForm(instance=request.user.profile,data=request.POST)
if user_edit_form.is_valid() and profile_edit_form.is_valid():
user_edit_form.save()
profile_edit_form.save()
messages.add_message(request,messages.SUCCESS,'profile updated')
return redirect('dashboard')
else:
return render(request,'accounts/edit_profile.html',{'user_edit_form':user_edit_form,
'profile_edit_form':profile_edit_form})
else:
user_edit_form = UserEditForm(instance=request.user)
profile_edit_form = ProfileEditForm(instance=request.user.profile)
return render(request,'accounts/edit_profile.html',{'user_edit_form':user_edit_form,
'profile_edit_form':profile_edit_form})
models.py
class Profile(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE,
primary_key=True)
first_name = models.CharField(max_length=30,blank=True)
last_name = models.CharField(max_length=30,blank=True)
DOB = models.DateField(null=True,blank=True)
mobile_no = models.IntegerField(null=True,blank=True)
address = models.TextField(max_length=250,blank=True)
signals.py
from accounts.models import Profile
def create_user_profile(sender, instance, created, **kwargs):
Profile.objects.create(user=instance)
apps.py
from django.apps import AppConfig
class AccountsConfig(AppConfig):
name = 'accounts'
def ready(self):
from django.db.models.signals import post_save
from accounts.signals import create_user_profile
from django.contrib.auth.models import User
post_save.connect(create_user_profile, sender=User,
dispatch_uid='create_user_profile')
错误:
Environment:
Request Method: POST
Request URL: http://example:8000/accounts/login/
Django Version: 2.1.1
Python Version: 3.6.4
Installed Applications:
['accounts.apps.AccountsConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'social_django']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "F:\schoolp\venv\lib\site-packages\django\db\backends\utils.py" in
_execute
85.return self.cursor.execute(sql, params)
The above exception (duplicate key value violates unique constraint
"accounts_profile_user_id_49a85d32_pk"
DETAIL: Key (user_id)=(5) already exists.
) was the direct cause of the following exception:
File "F:\schoolp\venv\lib\site-packages\django\core\handlers\exception.py"
in inner
34. response = get_response(request)
File "F:\schoolp\venv\lib\site-packages\django\core\handlers\base.py" in
_get_response
126. response = self.process_exception_by_middleware(e,
request)
File "F:\schoolp\venv\lib\site-packages\django\core\handlers\base.py" in
_get_response
124. response = wrapped_callback(request, *callback_args,
**callback_kwargs)
File "F:\schoolp\venv\lib\site-packages\django\views\generic\base.py" in
view
68. return self.dispatch(request, *args, **kwargs)
File "F:\schoolp\venv\lib\site-packages\django\utils\decorators.py" in
_wrapper
45. return bound_method(*args, **kwargs)
File "F:\schoolp\venv\lib\site-packages\django\views\decorators\debug.py" in
sensitive_post_parameters_wrapper
76. return view(request, *args, **kwargs)
File "F:\schoolp\venv\lib\site-packages\django\utils\decorators.py" in
_wrapper
45. return bound_method(*args, **kwargs)
File "F:\schoolp\venv\lib\site-packages\django\utils\decorators.py" in
_wrapped_view
142. response = view_func(request, *args, **kwargs)
File "F:\schoolp\venv\lib\site-packages\django\utils\decorators.py" in
_wrapper
45. return bound_method(*args, **kwargs)
File "F:\schoolp\venv\lib\site-packages\django\views\decorators\cache.py" in
_wrapped_view_func
44. response = view_func(request, *args, **kwargs)
File "F:\schoolp\venv\lib\site-packages\django\contrib\auth\views.py" in
dispatch
61. return super().dispatch(request, *args, **kwargs)
File "F:\schoolp\venv\lib\site-packages\django\views\generic\base.py" in
dispatch
88. return handler(request, *args, **kwargs)
File "F:\schoolp\venv\lib\site-packages\django\views\generic\edit.py" in
post
142. return self.form_valid(form)
File "F:\schoolp\venv\lib\site-packages\django\contrib\auth\views.py" in
form_valid
90. auth_login(self.request, form.get_user())
File "F:\schoolp\venv\lib\site-packages\django\contrib\auth\__init__.py" in
login
132. user_logged_in.send(sender=user.__class__, request=request,
user=user)
File "F:\schoolp\venv\lib\site-packages\django\dispatch\dispatcher.py" in
send
175. for receiver in self._live_receivers(sender)
File "F:\schoolp\venv\lib\site-packages\django\dispatch\dispatcher.py" in
<listcomp>
175. for receiver in self._live_receivers(sender)
File "F:\schoolp\venv\lib\site-packages\django\contrib\auth\models.py" in
update_last_login
20. user.save(update_fields=['last_login'])
File "F:\schoolp\venv\lib\site-packages\django\contrib\auth\base_user.py" in
save
73. super().save(*args, **kwargs)
File "F:\schoolp\venv\lib\site-packages\django\db\models\base.py" in save
718. force_update=force_update,
update_fields=update_fields)
File "F:\schoolp\venv\lib\site-packages\django\db\models\base.py" in
save_base
758. update_fields=update_fields, raw=raw, using=using,
File "F:\schoolp\venv\lib\site-packages\django\dispatch\dispatcher.py" in
send
175. for receiver in self._live_receivers(sender)
File "F:\schoolp\venv\lib\site-packages\django\dispatch\dispatcher.py" in
<listcomp>
175. for receiver in self._live_receivers(sender)
File "F:\schoolp\accounts\signals.py" in create_user_profile
4. Profile.objects.create(user=instance)
File "F:\schoolp\venv\lib\site-packages\django\db\models\manager.py" in
manager_method
82. return getattr(self.get_queryset(), name)(*args,
**kwargs)
File "F:\schoolp\venv\lib\site-packages\django\db\models\query.py" in create
413. obj.save(force_insert=True, using=self.db)
File "F:\schoolp\venv\lib\site-packages\django\db\models\base.py" in save
718. force_update=force_update,
update_fields=update_fields)
File "F:\schoolp\venv\lib\site-packages\django\db\models\base.py" in
save_base
748. updated = self._save_table(raw, cls, force_insert,
force_update, using, update_fields)
File "F:\schoolp\venv\lib\site-packages\django\db\models\base.py" in
_save_table
831. result = self._do_insert(cls._base_manager, using, fields,
update_pk, raw)
File "F:\schoolp\venv\lib\site-packages\django\db\models\base.py" in
_do_insert
869. using=using, raw=raw)
File "F:\schoolp\venv\lib\site-packages\django\db\models\manager.py" in
manager_method
82. return getattr(self.get_queryset(), name)(*args,
**kwargs)
File "F:\schoolp\venv\lib\site-packages\django\db\models\query.py" in
_insert
1136. return query.get_compiler(using=using).execute_sql(return_id)
File "F:\schoolp\venv\lib\site-packages\django\db\models\sql\compiler.py" in
execute_sql
1289. cursor.execute(sql, params)
File "F:\schoolp\venv\lib\site-packages\django\db\backends\utils.py" in
execute
100. return super().execute(sql, params)
File "F:\schoolp\venv\lib\site-packages\django\db\backends\utils.py" in
execute
68. return self._execute_with_wrappers(sql, params, many=False,
executor=self._execute)
File "F:\schoolp\venv\lib\site-packages\django\db\backends\utils.py" in
_execute_with_wrappers
77. return executor(sql, params, many, context)
File "F:\schoolp\venv\lib\site-packages\django\db\backends\utils.py" in
_execute
85. return self.cursor.execute(sql, params)
File "F:\schoolp\venv\lib\site-packages\django\db\utils.py" in __exit__
89. raise dj_exc_value.with_traceback(traceback) from
exc_value
File "F:\schoolp\venv\lib\site-packages\django\db\backends\utils.py" in
_execute
85. return self.cursor.execute(sql, params)
Exception Type: IntegrityError at /accounts/login/
Exception Value: duplicate key value violates unique constraint
"accounts_profile_user_id_49a85d32_pk"
DETAIL: Key (user_id)=(5) already exists.
答案 0 :(得分:0)
一旦您更新特定的用户实例,就会触发帖子保存。
def create_user_profile(sender, instance, created, **kwargs):
Profile.objects.get_or_create(user=instance)
或检查实例是否为新
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)