我有一个名为ScrummyUser的组织模型字段,与一个从AbstractUser模型继承的名为User的模型一对一字段,如何将表单字段中的数据保存到scrummyuser模型中?
这是组织模型
class Organization(models.Model):
organization = models.CharField(max_length=255, null=True)
def __str__(self):
return self.organization
这是ScrummyUser模型
class ScrummyUser(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name='scrummy_profile')
role= models.CharField(max_length=100, choices=role, blank=True, null=True, default='DEV')
org = models.ForeignKey(Organization, max_length=255, on_delete=models.CASCADE, default=1)
这是ScrummySignup表单
class ScrummySignUpForm(UserCreationForm):
role = forms.ChoiceField(choices=role, required=False)
org = forms.ModelChoiceField(
queryset=Organization.objects.all(),
widget=forms.Select
)
class Meta(UserCreationForm.Meta):
model = User
fields = ['first_name', 'last_name','username' ,'email']
@transaction.atomic
def save(self):
user = super().save(commit=False)
user.is_user = True
user.save()
scrummy = ScrummyUser.objects.create(user=user, role=role)
return user
它把这个错误消息扔给我
scrummy = ScrummyUser.objects.create(user=user, role=role, org=org)
NameError: name 'org' is not defined
这很明显,但是我正在寻找另一种保存数据的方法
答案 0 :(得分:0)
要使用摘要访问CutomUser
,您应该获得settings
的用户:
from django.conf import settings
class ScrummyUser(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,
primary_key=True, related_name='scrummy_profile')
答案 1 :(得分:0)
好的,所以我想出了这一点,在将变量org定义为modelchoicefield后,我将其传递给用户模型的字段作为用户表单字段,然后再将其保存到scrummyuser模型中。