我要如何修复Django管理和视图文件中的此错误?

huangapple go评论58阅读模式
英文:

how can I fix this error in Django admin and veiws files?

问题

在我的Account应用程序中,我有一个自定义用户模型的问题,我刚刚在我的setting.py中添加了AUTH_USER_MODEL = 'Account.User'

我遇到的问题是,当我转到管理员面板并在用户列表中点击用户时,我收到一个错误(这个错误不仅适用于用户模型,还适用于管理员面板中的所有其他模型;我不能删除或更新它们)。

在/admin/Account/user/1/delete/上的IntegrityError

FOREIGN KEY constraint failed

在/admin/Account/user/1/change/上的IntegrityError

FOREIGN KEY constraint failed

另外,如果我尝试使用我的注册视图注册用户,如果用户已存在于用户列表中,我会收到以下错误作为响应:

{
    "error": "用户名已被使用。"
}

用于检查电子邮件和用户名的注册视图类代码如下:

if User.objects.filter(email=email).exists():
    return Response(data={"error": "电子邮件已经被使用。"}, status=status.HTTP_400_BAD_REQUEST)

if User.objects.filter(username=username).exists():
    return Response(data={"error": "用户名已经被使用。"}, status=status.HTTP_400_BAD_REQUEST)

我的用户模型:

from django.db import models
from django.contrib.auth.models import AbstractUser, Group, Permission

class User(AbstractUser):
    id = models.AutoField(primary_key=True)
    email = models.EmailField(unique=True)
    full_name = models.CharField(max_length=255, default="")
    simple_description = models.CharField(max_length=255, default="tourist")
    biography = models.TextField(null=True, blank=True, default="")
    profile_picture = models.ImageField(null=True, blank=True)
    
    groups = models.ManyToManyField(Group, blank=True, related_name='account_users')
    user_permissions = models.ManyToManyField(Permission, blank=True, related_name='account_users')

    def __str__(self):
        return self.username

我的管理员代码:

from django.contrib import admin
from Destination.models import Destination, DestinationImages
from Account.models import User, Profile

class DestinationImagesInline(admin.TabularInline):
    model = DestinationImages

@admin.register(Destination)
class DestinationAdmin(admin.ModelAdmin):
    inlines = [DestinationImagesInline]

    list_display = ["id", "name", "category", "rating", "author"]
    list_filter = ["category", "rating"]
    search_fields = ["name", "author__username"]
    sortable_by = ["id"]

    fieldsets = (
        ("General Info", {
            "fields": ("author", "name", "rating")
        }),

        ("Details", {
            "fields": ("category", "description")
        }),

        ("Location", {
            "classes": ("collapse",),
            "fields": ("location",)
        }),
    )

class ProfileInline(admin.StackedInline):
    model = Profile

@admin.register(User)
class UserAdmin(admin.ModelAdmin):
    inlines = [ProfileInline]

    list_display = ['username', 'email', 'full_name', 'id', 'is_active', 'is_staff', 'is_superuser']
    search_fields = ['username', 'email', 'full_name']
    list_filter = ['is_staff', 'is_superuser', 'is_active']

    fieldsets = (
        (None, {
            'fields': ('username', 'email', 'password')
        }),

        ('Personal Info', {
            'fields': ('full_name', 'simple_description', 'biography', 'profile_picture')
        }),

        ('Permissions', {
            'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')
        }),

        ('Important dates', {
            'fields': ('last_login', 'date_joined')
        }),
    )

    readonly_fields = ('last_login', 'date_joined')

我还检查了在其他具有与模型的外键的每个字段中是否使用了on_delete=models.CASCADE

英文:

I have a problem with a custom User model in my Account app and I just put.

AUTH_USER_MODEL = 'Account.User' in my setting.py.

The problem I'm having is that when I go to the admin panel and click on a user in the Users list, I receive an error (this error is not only for the User model but also for all other models in the admin panel; I can't delete or update them).

IntegrityError at /admin/Account/user/1/delete/

FOREIGN KEY constraint failed

IntegrityError at /admin/Account/user/1/change/

FOREIGN KEY constraint failed

Also, if I try to register a user using my register view, I get this error, which I return as a response if the user already exists in the Users list.

{
"error": "Username has been already used."
}

The register view class code for checking the email and username:

if User.objects.filter(email=email).exists():
return Response(data={"error": "Email has been already used."},
status=status.HTTP_400_BAD_REQUEST)
if User.objects.filter(username=username).exists():
return Response(data={"error": "Username has been already used."},
status=status.HTTP_400_BAD_REQUEST)

My User Model:

from django.db import models
from django.contrib.auth.models import AbstractUser, Group, Permission
class User(AbstractUser):
id = models.AutoField(primary_key=True)
email = models.EmailField(unique=True)
full_name = models.CharField(max_length=255, default="")
simple_description = models.CharField(max_length=255, default="tourist")
biography = models.TextField(null=True, blank=True, default="")
profile_picture = models.ImageField(null=True, blank=True)
groups = models.ManyToManyField(Group, blank=True, related_name='account_users')
user_permissions = models.ManyToManyField(Permission, blank=True, related_name='account_users')
def __str__(self):
return self.username

My admin codes:

from django.contrib import admin
from Destination.models import Destination, DestinationImages
from Account.models import User, Profile
class DestinationImagesInline(admin.TabularInline):
model = DestinationImages
@admin.register(Destination)
class DestinationAdmin(admin.ModelAdmin):
inlines = [DestinationImagesInline]
list_display = ["id", "name", "category", "rating", "author"]
list_filter = ["category", "rating"]
search_fields = ["name", "author__username"]
sortable_by = ["id"]
fieldsets = (
("General Info", {
"fields": ("author", "name", "rating")
}),
("Details", {
"fields": ("category", "description")
}),
("Location", {
"classes": ("collapse",),
"fields": ("location",)
}),
)
class ProfileInline(admin.StackedInline):
model = Profile
@admin.register(User)
class UserAdmin(admin.ModelAdmin):
inlines = [ProfileInline]
list_display = ['username', 'email', 'full_name', 'id', 'is_active', 'is_staff', 'is_superuser']
search_fields = ['username', 'email', 'full_name']
list_filter = ['is_staff', 'is_superuser', 'is_active']
fieldsets = (
(None, {
'fields': ('username', 'email', 'password')
}),
('Personal Info', {
'fields': ('full_name', 'simple_description', 'biography', 'profile_picture')
}),
('Permissions', {
'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')
}),
('Important dates', {
'fields': ('last_login', 'date_joined')
}),
)
readonly_fields = ('last_login', 'date_joined')

I also checked that I used on_delete=models.CASCADE in every field in other models that have a Foreign Key with a model

答案1

得分: 1

似乎您已经使用Django的内置User模型创建了数据库表。然后您使用AUTH_USER_MODEL覆盖了默认的用户模型。但是AUTH_USER_MODEL引用的模型必须在其应用程序的第一个迁移(通常称为0001_initial)中创建,否则会出现依赖问题。

解决方案:

删除/丢弃整个数据库并重新执行迁移:

1- 在用户应用程序的迁移文件夹中,删除所有文件(例如001_initial.py)和pycache文件夹,但保留init.py。

2- 运行python manage.py makemigrations,然后运行python manage.py migrate

英文:

it seems you’ve created database tables with Django’s built-in User model . than you overrided the default user model with AUTH_USER_MODEL . but the model referenced by AUTH_USER_MODEL must be created in the first migration of its app (usually called 0001_initial); otherwise, you’ll have dependency issues.

Solution :

Delete/Drop the whole database and redo the migrations :

1- In the migrations folders of the USER app , delete all files (e.g. 001_initial.py) and pycache folder, except for init.py

2- Run python manage.py makemigrations Then run python manage.py migrate

答案2

得分: -1

请将User类中的id注释掉。这不是必需的。

class User(AbstractUser):
    #id = models.AutoField(
英文:

Please comment out id from class User. It is not required.

class User(AbstractUser):
#id = models.AutoField(

huangapple
  • 本文由 发表于 2023年7月3日 19:12:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76604193.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定