考虑以下代码:
class CandidateSignUpForm(forms.ModelForm):
first_name = forms.CharField(max_length=50, widget=forms.TextInput(attrs={'placeholder': 'Ime', 'class': 'validate'}))
last_name = forms.CharField(max_length=50, widget=forms.TextInput(attrs={'placeholder': _('Prezime'), 'class': 'validate'}))
class Meta:
model = User
fields = ('email', 'password', 'first_name', 'last_name')
widgets = {
'email': forms.EmailInput(
attrs = {
'placeholder': _('E-mail'),
'class': 'validate'
},
),
'password': forms.PasswordInput(
attrs = {
'placeholder': _('Lozinka'),
'class': 'validate'
},
),
}
def signup(self, user):
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.email = self.cleaned_data['email']
user.password = self.cleaned_data['password']
user.save()
candidate = Candidate()
candidate.user = user
candidate.save()
和我的模型。py:
class User(AbstractUser):
is_candidate = models.BooleanField(default=True)
is_employer = models.BooleanField(default=False)
is_admin = models.BooleanField(default=False)
first_name = models.CharField(max_length=50, null=True)
last_name = models.CharField(max_length=50, null=True)
mobile = models.IntegerField(null=True, unique=True)
address = models.CharField(max_length=250, null=True)
def __str__(self):
return self.email
class Candidate(models.Model):
user = models.OneToOneField(
User, on_delete=models.CASCADE, primary_key=True
)
available_from = models.DateField(blank=True, null=True)
dob = models.PositiveSmallIntegerField(blank = True, null=True)
about = models.TextField(max_length=500, blank = True, null=True)
def __str__(self):
return self.user.first_name + ' ' + self.user.last_name
现在,考虑到我正在使用Django AllAuth,我需要重写signup
方法,才能保存User
对象。使用上述代码,可以正确保存我的用户,而根本不保存候选对象,即候选表中没有记录。
我已经尝试了所有方法,但仍然无法弄清楚可能出了什么问题。
更新:
将candidate.user = user
更改为candidate.user = user.pk
也不起作用。
答案 0 :(得分:1)
您是否尝试过将候选模型与用户模型的ID链接起来? 因此,对于您的情况,像这样:
user = user.save()
candidate = Candidate.objects.create(user_id=user.id)
答案 1 :(得分:1)
我不认为您的方法正在被调用。首先,您需要将方法从def signup(self, request)
更改为def signup(self, request, user)
:
class CandidateSignUpForm(forms.Form):
first_name = forms.CharField(...)
last_name = forms.CharField(...)
def signup(self, request, user):
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.save()
candidate = Candidate()
candidate.user = user
candidate.save()
然后从这样的设置中指出:
ACCOUNT_SIGNUP_FORM_CLASS = 'PATH.TO.CandidateSignUpForm'
有关此替代的详细信息,请参见here