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

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

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

  1. FOREIGN KEY constraint failed

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

  1. FOREIGN KEY constraint failed

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

  1. {
  2. "error": "用户名已被使用。"
  3. }

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

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

我的用户模型:

  1. from django.db import models
  2. from django.contrib.auth.models import AbstractUser, Group, Permission
  3. class User(AbstractUser):
  4. id = models.AutoField(primary_key=True)
  5. email = models.EmailField(unique=True)
  6. full_name = models.CharField(max_length=255, default="")
  7. simple_description = models.CharField(max_length=255, default="tourist")
  8. biography = models.TextField(null=True, blank=True, default="")
  9. profile_picture = models.ImageField(null=True, blank=True)
  10. groups = models.ManyToManyField(Group, blank=True, related_name='account_users')
  11. user_permissions = models.ManyToManyField(Permission, blank=True, related_name='account_users')
  12. def __str__(self):
  13. return self.username

我的管理员代码:

  1. from django.contrib import admin
  2. from Destination.models import Destination, DestinationImages
  3. from Account.models import User, Profile
  4. class DestinationImagesInline(admin.TabularInline):
  5. model = DestinationImages
  6. @admin.register(Destination)
  7. class DestinationAdmin(admin.ModelAdmin):
  8. inlines = [DestinationImagesInline]
  9. list_display = ["id", "name", "category", "rating", "author"]
  10. list_filter = ["category", "rating"]
  11. search_fields = ["name", "author__username"]
  12. sortable_by = ["id"]
  13. fieldsets = (
  14. ("General Info", {
  15. "fields": ("author", "name", "rating")
  16. }),
  17. ("Details", {
  18. "fields": ("category", "description")
  19. }),
  20. ("Location", {
  21. "classes": ("collapse",),
  22. "fields": ("location",)
  23. }),
  24. )
  25. class ProfileInline(admin.StackedInline):
  26. model = Profile
  27. @admin.register(User)
  28. class UserAdmin(admin.ModelAdmin):
  29. inlines = [ProfileInline]
  30. list_display = ['username', 'email', 'full_name', 'id', 'is_active', 'is_staff', 'is_superuser']
  31. search_fields = ['username', 'email', 'full_name']
  32. list_filter = ['is_staff', 'is_superuser', 'is_active']
  33. fieldsets = (
  34. (None, {
  35. 'fields': ('username', 'email', 'password')
  36. }),
  37. ('Personal Info', {
  38. 'fields': ('full_name', 'simple_description', 'biography', 'profile_picture')
  39. }),
  40. ('Permissions', {
  41. 'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')
  42. }),
  43. ('Important dates', {
  44. 'fields': ('last_login', 'date_joined')
  45. }),
  46. )
  47. 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/

  1. FOREIGN KEY constraint failed

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

  1. 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.

  1. {
  2. "error": "Username has been already used."
  3. }

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

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

My User Model:

  1. from django.db import models
  2. from django.contrib.auth.models import AbstractUser, Group, Permission
  3. class User(AbstractUser):
  4. id = models.AutoField(primary_key=True)
  5. email = models.EmailField(unique=True)
  6. full_name = models.CharField(max_length=255, default="")
  7. simple_description = models.CharField(max_length=255, default="tourist")
  8. biography = models.TextField(null=True, blank=True, default="")
  9. profile_picture = models.ImageField(null=True, blank=True)
  10. groups = models.ManyToManyField(Group, blank=True, related_name='account_users')
  11. user_permissions = models.ManyToManyField(Permission, blank=True, related_name='account_users')
  12. def __str__(self):
  13. return self.username

My admin codes:

  1. from django.contrib import admin
  2. from Destination.models import Destination, DestinationImages
  3. from Account.models import User, Profile
  4. class DestinationImagesInline(admin.TabularInline):
  5. model = DestinationImages
  6. @admin.register(Destination)
  7. class DestinationAdmin(admin.ModelAdmin):
  8. inlines = [DestinationImagesInline]
  9. list_display = ["id", "name", "category", "rating", "author"]
  10. list_filter = ["category", "rating"]
  11. search_fields = ["name", "author__username"]
  12. sortable_by = ["id"]
  13. fieldsets = (
  14. ("General Info", {
  15. "fields": ("author", "name", "rating")
  16. }),
  17. ("Details", {
  18. "fields": ("category", "description")
  19. }),
  20. ("Location", {
  21. "classes": ("collapse",),
  22. "fields": ("location",)
  23. }),
  24. )
  25. class ProfileInline(admin.StackedInline):
  26. model = Profile
  27. @admin.register(User)
  28. class UserAdmin(admin.ModelAdmin):
  29. inlines = [ProfileInline]
  30. list_display = ['username', 'email', 'full_name', 'id', 'is_active', 'is_staff', 'is_superuser']
  31. search_fields = ['username', 'email', 'full_name']
  32. list_filter = ['is_staff', 'is_superuser', 'is_active']
  33. fieldsets = (
  34. (None, {
  35. 'fields': ('username', 'email', 'password')
  36. }),
  37. ('Personal Info', {
  38. 'fields': ('full_name', 'simple_description', 'biography', 'profile_picture')
  39. }),
  40. ('Permissions', {
  41. 'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')
  42. }),
  43. ('Important dates', {
  44. 'fields': ('last_login', 'date_joined')
  45. }),
  46. )
  47. 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注释掉。这不是必需的。

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

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

  1. class User(AbstractUser):
  2. #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:

确定