我正在尝试将用户模型更改为自定义模型。我不介意删除数据库而仅使用一个新数据库,但是当我尝试运行makemigrations时,会出现此错误
bookings.Session.session_client: (fields.E301) Field defines a relation with the model 'auth.User', which has been swapped out.
HINT: Update the relation to point at 'settings.AUTH_USER_MODEL'.
booking / views.py
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from bookings.models import Session
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
# Create your views here.
def book(request, Session_id):
lesson = get_object_or_404(Session, pk=Session_id)
try:
client = request.user.id
except (KeyError, Choice.DoesNotExist):
return render(request, 'booking/details.html', {
'lesson': lesson,
'error_message': "You need to login first",
})
else:
lesson.session_client.add(client)
lesson.save()
return HttpResponseRedirect("")
settings.py
INSTALLED_APPS = [
#Custom apps
'mainapp.apps.MainappConfig',
'bookings.apps.BookingsConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
AUTH_USER_MODEL = 'mainapp.CustomUser'
bookings / models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Session(models.Model):
session_title = models.CharField(max_length=300)
session_time = models.DateTimeField("Time of session")
session_difficulty = models.CharField(max_length=200)
session_duration = models.IntegerField()
session_description = models.TextField()
session_client = models.ManyToManyField(User, blank=True)
def __str__(self):
return self.session_title
我正在尝试将用户模型更改为abstractuser。
答案 0 :(得分:1)
在views.py
from django.conf import settings
User = settings.AUTH_USER_MODEL
并删除from django.contrib.auth.models import User
答案 1 :(得分:1)
我有同样的错误, 从此更改模型字段:
user = models.ForeignKey(to=User, on_delete=models.CASCADE)
为此:
user = models.ForeignKey(to=MyUser, on_delete=models.CASCADE)
MyUser 是您的自定义用户模型
答案 2 :(得分:0)
问题是booking / models.py中的这一行:
session_client = models.ManyToManyField(User, blank=True)
您有一个要用户的ManyToManyField,但是您设置了其他用户模型。
因此,在该字段中,删除User的导入,添加
from django.conf import settings
并将模型线更改为
session_client = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True)
编辑:HenryM指出,views.py中还有另一个类似的问题。
答案 3 :(得分:0)
因为在settings.py中已定义
AUTH_USER_MODEL = 'user.User'
我添加了user.User而不是auth.User
user = models.ForeignKey('user.User', on_delete=models.CASCADE)
答案 4 :(得分:0)
变化:
from django.contrib.auth.models import User
致:
from django.contrib.auth import get_user_model
User = get_user_model()