如何修复 Field 定义了与模型“auth.User”的关系,该模型已被换出

Leo*_*123 6 python django

我正在尝试将我的用户模型更改为自定义模型。我不介意删除我的数据库并只使用一个新数据库,但是当我尝试运行 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'.
Run Code Online (Sandbox Code Playgroud)

预订/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("")
Run Code Online (Sandbox Code Playgroud)

设置.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'
Run Code Online (Sandbox Code Playgroud)

预订/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   
Run Code Online (Sandbox Code Playgroud)

我正在尝试将用户模型更改为抽象用户。

Rem*_*ich 8

问题是booking/models.py中的这一行:

session_client = models.ManyToManyField(User, blank=True) 
Run Code Online (Sandbox Code Playgroud)

您对 User 有一个 ManyToManyField,但您设置了不同的 User 模型。

因此,在该字段中删除用户的导入,添加

from django.conf import settings
Run Code Online (Sandbox Code Playgroud)

并将模型线更改为

session_client = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True)
Run Code Online (Sandbox Code Playgroud)

编辑:在 views.py 中有另一个类似的问题,正如 HenryM 所指出的。


Hen*_*ryM 7

包括以下内容 views.py

from django.conf import settings
User = settings.AUTH_USER_MODEL
Run Code Online (Sandbox Code Playgroud)

并删除 from django.contrib.auth.models import User


小智 5

改变:

from django.contrib.auth.models import User
Run Code Online (Sandbox Code Playgroud)

到:

from django.contrib.auth import get_user_model
User = get_user_model()
Run Code Online (Sandbox Code Playgroud)