我正在用django开始我的第一个webproject,
- 我创建了一个APP“核心”来处理注册和登录
- 在注册期间,我希望用户提交一些额外的信息 创建Userprofile
-I扩展了Django与OneToOne
关系的默认用户模型
我尝试上传文件时遇到此错误
回溯:
File "C:\Python36\lib\site-packages\django\db\backends\utils.py" in execute
65. return self.cursor.execute(sql, params)
File "C:\Python36\lib\site-packages\django\db\backends\sqlite3\base.py" in
execute
328. return Database.Cursor.execute(self, query, params)
The above exception (UNIQUE constraint failed: core_profile.user_id) was the
direct cause of the following exception:
File "C:\Python36\lib\site-packages\django\core\handlers\exception.py" in
inner
41. response = get_response(request)
File "C:\Python36\lib\site-packages\django\core\handlers\base.py" in
_get_response
187. response = self.process_exception_by_middleware(e,
request)
File "C:\Python36\lib\site-packages\django\core\handlers\base.py" in
_get_response
185. response = wrapped_callback(request, *callback_args,
**callback_kwargs)
File "C:\djangoprojects\mysite\mysite\core\views.py" in upload_files
92. document.save()
File "C:\Python36\lib\site-packages\django\db\models\base.py" in save
806. force_update=force_update,
update_fields=update_fields)
File "C:\Python36\lib\site-packages\django\db\models\base.py" in save_base
836. updated = self._save_table(raw, cls, force_insert,
force_update, using, update_fields)
File "C:\Python36\lib\site-packages\django\db\models\base.py" in _save_table
922. result = self._do_insert(cls._base_manager, using,
fields, update_pk, raw)
File "C:\Python36\lib\site-packages\django\db\models\base.py" in _do_insert
961. using=using, raw=raw)
File "C:\Python36\lib\site-packages\django\db\models\manager.py" in
manager_method
85. return getattr(self.get_queryset(), name)(*args,
**kwargs)
File "C:\Python36\lib\site-packages\django\db\models\query.py" in _insert
1060. return
query.get_compiler(using=using).execute_sql(return_id)
File "C:\Python36\lib\site-packages\django\db\models\sql\compiler.py" in
execute_sql
1099. cursor.execute(sql, params)
File "C:\Python36\lib\site-packages\django\db\backends\utils.py" in execute
80. return super(CursorDebugWrapper, self).execute(sql,
params)
File "C:\Python36\lib\site-packages\django\db\backends\utils.py" in execute
65. return self.cursor.execute(sql, params)
File "C:\Python36\lib\site-packages\django\db\utils.py" in __exit__
94. six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:\Python36\lib\site-packages\django\utils\six.py" in reraise
685. raise value.with_traceback(tb)
File "C:\Python36\lib\site-packages\django\db\backends\utils.py" in execute
65. return self.cursor.execute(sql, params)
File "C:\Python36\lib\site-packages\django\db\backends\sqlite3\base.py" in
execute
328. return Database.Cursor.execute(self, query, params)
Exception Type: IntegrityError at /core/upload_files/
Exception Value: UNIQUE constraint failed: core_profile.user_id
我的一些代码:
模型:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
birth_date = models.DateField(null=True, blank=True)
birth_place = models.CharField(max_length=80, verbose_name= ("Lieu de
Naissance"))
email_confirmed = models.BooleanField(default=False)
adress = models.CharField(max_length=80, verbose_name=("Adresse"))
adress_complement = models.CharField(max_length=80, verbose_name=
("Complément d'Adresse"))
city = models.CharField(max_length=80, verbose_name=("Ville"))
zip_code = models.IntegerField(null=True, blank=True)
drive_licence_num = models.CharField(max_length=80, verbose_name=("N° du
Permis de conduire"))
social_secu_num = models.IntegerField(null=True, blank=True)
phone_number = models.IntegerField(null=True, blank=True)
profile_completed = models.BooleanField(default=False)
#DOCUMENTS TO UPLOAD
id_card = models.FileField(('Carte Nationale d\'Identité'))
drive_licence = models.FileField(('Permis de conduire'))
police_record = models.FileField(('Casier judiciaire'))
medical_visit = models.FileField(('Visite médicale'))
rib = models.FileField(('Relevé d\'Identité Bancaire (RIB)'))
uploaded_at = models.DateTimeField(auto_now_add=True)
docs_are_checked = models.BooleanField(default=False)
def __str__(self):
return self.user.username
@receiver(post_save, sender=User)
def update_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
instance.profile.save()
形式:
class SignUpForm(UserCreationForm):
email = forms.EmailField(max_length=254, help_text='Required. Inform a
valid email address.')
class Meta:
model = User
fields = ('first_name', 'last_name', 'email', 'username', 'password1',
'password2',)
class ProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = ('birth_date','birth_place', 'adress', 'adress_complement',
'city', 'zip_code', 'drive_licence_num',
'social_secu_num','phone_number')
class DocumentForm(forms.ModelForm):
id_card = forms.FileField(('Carte Nationale d\'Identité'),
help_text='Required. Recto / Verso.')
class Meta:
model = Profile
fields = ('id_card', 'drive_licence',
'police_record', 'medical_visit', 'rib',)
的观点:
def complete_profile(request):
if request.user.is_authenticated():
if request.method == 'POST':
form = ProfileForm(request.POST, instance=request.user.profile)
if form.is_valid():
profile = form.save(commit=False)
profile.profile_completed = True
profile.save()
return redirect('upload_files')
else:
form = ProfileForm()
return render(request, 'complete_profile.html', {'form': form})
else:
return redirect('login')
def upload_files(request):
if request.user.is_authenticated():
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
document = form.save(commit=False)
document.user = request.user
document.save()
return render(request, 'home.html')
else:
form = DocumentForm()
return render(request, 'upload_files.html', {'form': form})
else:
return render(request, 'login.html')
答案 0 :(得分:1)
我无法准确解释您收到错误的原因。但是,由于您在信号处理程序中创建配置文件,我认为您应该将实例传递给表单。这意味着您不必再在document.user
块中设置if form.is_valid()
。
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES, instance=request.user.profile)
if form.is_valid():
document = form.save()
return render(request, 'home.html')
else:
form = DocumentForm(instance=request.user.profile)
请注意,建议在成功发布请求后重定向用户,以防止重复提交。
if form.is_valid():
document = form.save()
return redirect('/')