Я хочу, чтобы мой администратор мог войти в систему и создавать пользователей в моем приложении Django, но каждый раз, когда я пытаюсь создать пользователя, я получаю это сообщение об ошибке
IntegrityError at /backoffice/add-exco/
(1062, "Duplicate entry '1' for key 'user_id'")
Подход, который я использовал, был расширить модель пользователя, используя ссылку один на один. Я также видел сообщение о стековерсии потока, предлагающее, как решить эту проблему следующим образом:
- Измените свой OneToOneField на ForeignKey
- В проверке формы убедитесь, что запись не существует
- При создании формы проверьте, существует ли уже запись, а затем разрешите пользователю ее редактировать.
Полная ошибка трассировки
Traceback (most recent call last):
File "C:\Users\Benedict\Miniconda3\envs\django3\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\Benedict\Miniconda3\envs\django3\lib\site-packages\django\db\backends\mysql\base.py", line 71, in execute
return self.cursor.execute(query, args)
File "C:\Users\Benedict\Miniconda3\envs\django3\lib\site-packages\MySQLdb\cursors.py", line 209, in execute
res = self._query(query)
File "C:\Users\Benedict\Miniconda3\envs\django3\lib\site-packages\MySQLdb\cursors.py", line 315, in _query
db.query(q)
File "C:\Users\Benedict\Miniconda3\envs\django3\lib\site-packages\MySQLdb\connections.py", line 239, in query
_mysql.connection.query(self, query)
MySQLdb._exceptions.IntegrityError: (1062, "Duplicate entry '3' for key 'user_id'")
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Benedict\Miniconda3\envs\django3\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\Benedict\Miniconda3\envs\django3\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\Benedict\Miniconda3\envs\django3\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Benedict\Miniconda3\envs\django3\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "D:\mycda\backend\views.py", line 43, in add_exco
form2.save()
File "C:\Users\Benedict\Miniconda3\envs\django3\lib\site-packages\django\db\models\base.py", line 741, in save
force_update=force_update, update_fields=update_fields)
File "C:\Users\Benedict\Miniconda3\envs\django3\lib\site-packages\django\db\models\base.py", line 779, in save_base
force_update, using, update_fields,
File "C:\Users\Benedict\Miniconda3\envs\django3\lib\site-packages\django\db\models\base.py", line 870, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "C:\Users\Benedict\Miniconda3\envs\django3\lib\site-packages\django\db\models\base.py", line 908, in _do_insert
using=using, raw=raw)
File "C:\Users\Benedict\Miniconda3\envs\django3\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\Benedict\Miniconda3\envs\django3\lib\site-packages\django\db\models\query.py", line 1186, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "C:\Users\Benedict\Miniconda3\envs\django3\lib\site-packages\django\db\models\sql\compiler.py", line 1335,
in execute_sql
cursor.execute(sql, params)
File "C:\Users\Benedict\Miniconda3\envs\django3\lib\site-packages\django\db\backends\utils.py", line 99, in execute
return super().execute(sql, params)
File "C:\Users\Benedict\Miniconda3\envs\django3\lib\site-packages\django\db\backends\utils.py", line 67, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "C:\Users\Benedict\Miniconda3\envs\django3\lib\site-packages\django\db\backends\utils.py", line 76, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Users\Benedict\Miniconda3\envs\django3\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\Benedict\Miniconda3\envs\django3\lib\site-packages\django\db\utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\Benedict\Miniconda3\envs\django3\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\Benedict\Miniconda3\envs\django3\lib\site-packages\django\db\backends\mysql\base.py", line 71, in execute
return self.cursor.execute(query, args)
File "C:\Users\Benedict\Miniconda3\envs\django3\lib\site-packages\MySQLdb\cursors.py", line 209, in execute
res = self._query(query)
File "C:\Users\Benedict\Miniconda3\envs\django3\lib\site-packages\MySQLdb\cursors.py", line 315, in _query
db.query(q)
File "C:\Users\Benedict\Miniconda3\envs\django3\lib\site-packages\MySQLdb\connections.py", line 239, in query
_mysql.connection.query(self, query)
django.db.utils.IntegrityError: (1062, "Duplicate entry '3' for key 'user_id'")
[04/Apr/2020 20:33:21] "POST /backoffice/add-exco/ HTTP/1.1" 500 181244
Я не знаю, как go около 2, 3 есть лучший подход? Ниже мой код на models.py
class AdditionalProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
mobile1 = models.CharField(max_length=15)
mobile2 = models.CharField(max_length=15, blank=True, null=True)
occupation = models.CharField(max_length=5, choices=OCCUPATION_FIELD, default=CHOOSE)
job_cader = models.CharField(max_length=5, choices=JOB_CADER, default=CHOOSE_JOB)
profile = models.ImageField(blank=True, null=True, upload_to='backend/')
def __str__(self):
return self.user.username
на forms.py
class RegisterForm(UserCreationForm):
class Meta():
model = User
fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2')
def save(self, commit=True):
user = super().save(commit=False)
user.username = self.cleaned_data['username']
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.email = self.cleaned_data['email']
if commit:
user.save()
return user
class UserProfileForm(forms.ModelForm):
class Meta():
model = AdditionalProfile
exclude = ('user',)
widgets = {
'mobile1':forms.TextInput(attrs={'class':'form-control', 'placeholder':'Mobile No 1'}),
'mobile2':forms.TextInput(attrs={'class':'form-control', 'placeholder':'Mobile No 2'}),
'occupation':forms.Select(choices=OCCUPATION_FIELD, attrs={'class':'form-control'}),
'job_cader':forms.Select(choices=JOB_CADER, attrs={'class':'form-control'}),
'profile':forms.ClearableFileInput(attrs={'class':'form-control'})
}
на views.py
@login_required(login_url='/backoffice/')
def add_exco(request):
if request.method == 'POST':
register_form = RegisterForm(request.POST)
extend_form = UserProfileForm(request.POST, request.FILES)
if register_form.is_valid() and extend_form.is_valid():
form1 = register_form.save()
form2 = extend_form.save(commit=False)
form2.user = form1
form2.save()
messages.success(request, 'An Exco have been registered successfully')
register_form = RegisterForm()
extend_form = UserProfileForm(request.POST, request.FILES)
else:
register_form = RegisterForm()
extend_form = UserProfileForm()
return render(request, 'dashboard/add-exco.html', {'reg':register_form, 'ext':extend_form})