首页 > 解决方案 > Django - 将工作人员设置为新用户的默认值

问题描述

大家!

我正在尝试将新用户设置为默认的 staff_member,但我找不到任何解决方案。我真的需要帮助。我的代码如下。

楷模

class Participante(models.Model):
    nome = models.CharField(max_length=100)
    cpf = models.CharField(max_length=13)
    email = models.EmailField()
    dt_criacao = models.DateTimeField(auto_now=True)
    is_staff = models.BooleanField(
        ('staff status'),
        default=True,
        help_text=('Designates whether the user can log into this admin site.'),
    )

    def __str__(self):
        return self.nome

形式

class ParticipanteForm(UserCreationForm):

    first_name = forms.CharField(max_length=100, label='Primeiro nome')
    last_name = forms.CharField(max_length=100, label='Último nome')
    class Meta:
        model = User
        fields = ['username', 'first_name', 'last_name', 'email', 'password1', 'password2'] 

意见

def cadastro(request):
    form = ParticipanteForm()

    if request.method == 'POST':
        form = ParticipanteForm(request.POST)
        
        if form.is_valid():
            #User(request, username=username, password=password1)
            form.save()
            return redirect('dashboard')

    return render(request, 'cadastro.html', locals())

标签: pythondjangodjango-admin

解决方案


我认为这里的问题是您UserCreationForm指向User模型而不是您的自定义Participante模型。因此,用户不会被保存在您期望的表中。

settings.py中,将Participante模型设置为您的用户模型(您的Participante模型还必须继承AbstractUser以保留User模型的方法等。

阅读:https ://docs.djangoproject.com/en/3.1/topics/auth/customizing/#django.contrib.auth.models.AbstractUser

# settings.py
AUTH_USER_MODEL = 'your_app.models.Participante'
# your_app.models
from django.contrib.auth.models import AbstractUser

class Participante(AbstractUser):
    nome = models.CharField(max_length=100)
    cpf = models.CharField(max_length=13)
    email = models.EmailField()
    dt_criacao = models.DateTimeField(auto_now=True)
    is_staff = models.BooleanField(
        ('staff status'),
        default=True,
        help_text=('Designates whether the user can log into this admin site.'),
    )

    def __str__(self):
        return self.nome

然后在您的表格中,指向您的AUTH_USER_MODEL使用get_user_model()

# forms.py
from django.contrib.auth import get_user_model

class ParticipanteForm(UserCreationForm):

    first_name = forms.CharField(max_length=100, label='Primeiro nome')
    last_name = forms.CharField(max_length=100, label='Último nome')
    class Meta:
        model = get_user_model()
        fields = ['username', 'first_name', 'last_name', 'email', 'password1', 'password2']```


推荐阅读