我收到以下错误:UNIQUE constraint failed: user_profile_credit.customer_id
我尝试将当前用户的ID分配给模型
models.py
class Credit(models.Model):
WALLET=(
('1','first choice'),
('2','second choice')
)
customer=models.OneToOneField(User)
wallet=models.CharField(max_length=2, choices= WALLET)
和我的form.py
class CreditForm(forms.ModelForm):
class Meta:
model=Credit
fields=['wallet']
widgets = {
'wallet': forms.RadioSelect(),
}
最后我的views.py:
def CreditView(request):
if request.method == "POST":
form = CreditForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.customer=request.user #:((
post.save()
return redirect('user_profile:index')
else:
form = CreditForm()
return render(request, 'user_profile/credit.html', {'form': form})
我甚至改变了:
post.customer=request.user
为:
post.customer=User.objects.filter(id= request.user.id)[0]
和
currentuser=request.user
post.customer=currentuser.id
但我收到错误Cannot assign "5": "Credit.customer" must be a "User" instance.
答案 0 :(得分:0)
使用:
form = CreditForm(request.POST, instance=request.user.credit)
(这假设您已经为此用户创建了一个信用实例。详细了解OneToOneField
s here)。