在models.py中有一个用户模型-
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(unique=False)
username = models.CharField(primary_key=True, max_length=25, unique=True)
password = models.CharField(max_length=50)
我以前没有primary_key = True键,但是最近添加了它。但是,添加之后,我得到了错误:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 303, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: foreign key mismatch - "app_user_groups" referencing "app_user"
“ app”是我的应用程序的名称。我以前从未听说过“ app_user_groups”(没有任何型号具有该名称,等等。)。
在models.py中添加字段后,我确保运行:
python3 manage.py makemigrations app
python3 manage.py migrate
当我尝试注册新用户(我清除了迁移文件夹)时,发生错误。具体来说,错误位于
user = form.save()
在添加primary_key = True之前,此过程可以正常工作。
有人知道我为什么突然遇到这个问题以及如何解决它吗?
views.py
def signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
usermodel = get_user_model()
username = form.cleaned_data['username']
password = form.cleaned_data['password1']
email = form.cleaned_data['email']
user = form.save()
login(request, user)
return HttpResponseRedirect('/home')
else:
form = SignUpForm()
return render(request, "signup.html", {'form': form})