gpt4 book ai didi

python - 比较表单字段值和查询集值的值

转载 作者:太空宇宙 更新时间:2023-11-03 20:18:32 25 4
gpt4 key购买 nike

在我的应用程序中,注册表单如下所示:

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")

关于python - 比较表单字段值和查询集值的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58298910/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com