python - 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())
解决方案
我认为这里的问题是您UserCreationForm
指向User
模型而不是您的自定义Participante
模型。因此,用户不会被保存在您期望的表中。
在settings.py
中,将Participante
模型设置为您的用户模型(您的Participante
模型还必须继承AbstractUser
以保留User
模型的方法等。
# 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']```
推荐阅读
- sql - 如何检查数据库行的所有实例是否相同,如果是,则在 SQL 中计数 + 1?
- javascript - Instagram 公共 API (/?__a=1) 有效,但仅在某些时候有效
- ibm-cloud - Watson Assistant 和 node-red
- r - 改进和加速代码以确定大量组合
- azure-devops - 基于一组布尔参数创建 MSBuild 参数字符串
- discord - 在 DiscordJS 中删除消息通知
- javascript - 使用可变元素 ID 时,jQuery 如何区分函数调用(例如点击时)?
- .net - 库 System.Threading.Tasks.Extensions 未在 Azure Web 应用上加载
- delphi - 直接在 Delphi IDE 编辑器中显示 Subversion 差异
- algorithm - 如何可视化 3 路归并排序?