Django 保存用户时出现错误,找不到基于选项的角色。

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

Django save User error not finding role based on choices

问题

我有这个用于用户的models.py文件:

from django.contrib.auth.models import AbstractUser
from django.db.models import CharField
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from django.db import models
from django.db.utils import IntegrityError

class Role(models.Model): # 如果要更改角色,请参考上面的注释
    ADMIN = 'ADMIN'
    SELLER = 'SELLER'
    SALES_DIRECTOR = 'SALES_DIRECTOR'
    SALES_ASSISTANT = 'SALES_ASSISTANT'
    OPERATIONS = 'OPERATIONS'
    ROLE_CHOICES = [
        (ADMIN, 'Administrator'),
        (SELLER, 'Seller'),
        (SALES_DIRECTOR, 'Sales Director'),
        (SALES_ASSISTANT, 'Sales Assistant'),
        (OPERATIONS, 'Operations'),
    ]
    role = models.CharField(
        max_length=20,
        choices=ROLE_CHOICES,
        default=SELLER,
    )

    def __str__(self):  # 这里
        return self.role

class User(AbstractUser):
    # Orphea的默认自定义用户模型
    # 如果需要在用户注册时填写字段,请相应地检查forms.SignupForm和forms.SocialSignupForms。
    
    # 名字不涵盖全球范围内的名称模式
    name = CharField(_('用户名称'), blank=True, max_length=255)
    first_name = None  # 类型:忽略
    last_name = None  # 类型:忽略
    role = models.ForeignKey(Role, on_delete=models.SET_NULL, null=True)
    
    def get_absolute_url(self):
        # 获取用户详细视图的URL
        return reverse("users:detail", kwargs={"username": self.username})
    
    @property
    def role_choices(self):
        return [(role.id, role.role) for role in Role.objects.all()]
    
    def save(self, *args, **kwargs):
        # 检查是否存在所选角色的角色实例
        role, created = Role.objects.get_or_create(role=self.role)
        # 将角色实例分配给用户
        self.role = role
        super().save(*args, **kwargs)

我的角色表包含:

pk, role:
6, ADMIN
7, SELLER
8, SALES_DIRECTOR
9, SALES_ASSISTANT
10, OPERATIONS

当尝试保存用户时,我遇到以下错误:

在/admin/users/user/1/change/处的ValueError
无法分配'ADMIN':'User.role'必须是“Role”实例。
我不知道该如何修复它。
目标是维护角色选择并检查角色是否存在于列表中,然后更新分配了角色的用户。每个用户只有一个角色。
英文:

I've this models.py for user:

from django.contrib.auth.models import AbstractUser
from django.db.models import CharField
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from django.db import models
from django.db.utils import IntegrityError

"""
Pour toute modification des roles possibles, il faut lancer dans le terminal
python3 manage.py create_roles

Pour voir le code correspondant, il faut aller dans le repertoire management/commands/
C est une commande cree expres pour cette fonctionnalité

"""

class Role(models.Model): # si changement de roles voir ci dessus le commentaire
    ADMIN = 'ADMIN'
    SELLER = 'SELLER'
    SALES_DIRECTOR = 'SALES_DIRECTOR'
    SALES_ASSISTANT = 'SALES_ASSISTANT'
    OPERATIONS = 'OPERATIONS'
    ROLE_CHOICES = [
        (ADMIN, 'Administrator'),
        (SELLER, 'Seller'),
        (SALES_DIRECTOR, 'Sales Director'),
        (SALES_ASSISTANT, 'Sales Assistant'),
        (OPERATIONS, 'Operations'),
    ]
    role = models.CharField(
        max_length=20,
        choices=ROLE_CHOICES,
        default=SELLER,
    )

    def __str__(self):  # Here
        return self.role


class User(AbstractUser):
    """
    Default custom user model for Orphea.
    If adding fields that need to be filled at user signup,
    check forms.SignupForm and forms.SocialSignupForms accordingly.
    """

    #: First and last name do not cover name patterns around the globe
    name = CharField(_("Name of User"), blank=True, max_length=255)
    first_name = None  # type: ignore
    last_name = None  # type: ignore
    role = models.ForeignKey(Role, on_delete=models.SET_NULL, null=True)
    def get_absolute_url(self):
        """Get url for user's detail view.

        Returns:
            str: URL for user detail.

        """
        return reverse("users:detail", kwargs={"username": self.username})

    @property
    def role_choices(self):
        return [(role.id, role.role) for role in Role.objects.all()]

    def save(self, *args, **kwargs):
        # Check if role instance exists for selected role
        role, created = Role.objects.get_or_create(role=self.role)
        # Assign the role instance to the user
        self.role = role
        super().save(*args, **kwargs)

My role table contains :

pk, role  : 
6,ADMIN
7,SELLER
8,SALES_DIRECTOR
9,SALES_ASSISTANT
10,OPERATIONS

I've this error when trying to save a user :
ValueError at /admin/users/user/1/change/
Cannot assign "'ADMIN'": "User.role" must be a "Role" instance.

I don't know how to fix it.

Objectif is to maintain role choices and to check if role exists in list and then update user with role assigned. each user have only one role.

答案1

得分: 0

问题出在我的admin.py文件中:我在ChoiceField中放置了角色,但它与角色对象不匹配。

class UserAdminForm(forms.ModelForm):

    # role = forms.ChoiceField(choices=Role.ROLE_CHOICES)
    role = Role.objects.all()

    class Meta:
        model = get_user_model()
        fields = '__all__'
英文:

The issue was in my admin.py: I put role from choiceField but it doesn't t not fit with a role object.

class UserAdminForm(forms.ModelForm):

    #role = forms.ChoiceField(choices=Role.ROLE_CHOICES)
    role = Role.objects.all()

    class Meta:
        model = get_user_model()
        fields = '__all__'

huangapple
  • 本文由 发表于 2023年2月27日 06:45:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/75575444.html
匿名

发表评论

匿名网友

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

确定