在我的应用程序中,注册表单如下所示:
Forms.py
class EmployeeSignUpForm(UserCreationForm):
company = forms.ModelChoiceField(queryset=Company.objects.all(), required=True, label='Select Company')
c_code = forms.IntegerField(required=True)
class Meta(UserCreationForm.Meta):
model = User
@transaction.atomic
def save (self):
user = super().save(commit=False)
user.is_employee = True
user.save()
c_company = self.cleaned_data['company'][0]
employee = Employee.objects.create(user=user, company=c_company)
return user
如何将c_code与models.py中的company_code进行比较,并仅在两者匹配时保存表单,否则会引发错误?
模型.py
class Company(models.Model):
company_name = models.CharField(max_length=255, default=0)
company_email = models.EmailField(max_length=255, default=0)
company_phone = models.CharField(max_length=255, default=0)
company_code = models.IntegerField(default=0)
def __str__ (self):
return self.company_name
你可以这样做:
def clean_c_code(self):
c_code = int(self.cleaned_data['c_code'])
try:
Company.objects.get(c_code=c_code)
except Company.DoesNotExist:
raise ValidationError("Don't save")
我是一名优秀的程序员,十分优秀!