我无法继续我的项目。我尝试用正确的用户名和密码注册用户/登录,但它给了我一个错误;
ValueError: Cannot force an update in save() with no primary key.
Views.py
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.forms import UserCreationForm
from django.contrib import messages
from .models import Profile, Order, BuyOffer
from django.views.decorators.csrf import csrf_exempt
from .forms import OrderForm, BuyForm
import requests
def login_user(request):
price = get_price()
if request.method == "POST":
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('profile')
else:
messages.success(request, 'There was an error logging in, try again...')
return render(request, 'app/login_user.html', {'price': price})
else:
return render(request, 'app/login_user.html', {'price': price})
问题是一致的
login(request, user)
Models.py
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
class Profile(models.Model):
user_profile=models.ForeignKey(User,on_delete=models.CASCADE)
btc=models.IntegerField(default=5)
usd=models.IntegerField(default=100000)
initial_balance=models.IntegerField()
1条答案
按热度按时间s4n0splo1#
尝试在不指定主键的情况下将对象保存到数据库时,会引发错误消息
"ValueError: Cannot force an update in save() with no primary key."
。1.请确保传递给
login
函数的用户对象是有效的用户对象,并且它有主键。您可以通过调用user.pk
来检查这一点,并确保它返回非空值。1.确保您已使用表单中提供的相同用户名和密码创建超级用户。
1.确保
user
对象是User
模型的示例或其子类。1.在您的
Profile
模型中,您应该使用OneToOneField
而不是ForeignKey
,因为每个用户只有一个配置文件,并且还要确保使用specify unique=True
。