我最近决定更新我的Django项目的forms.py文件,使其中一个字段变成一个下拉菜单而不是一个空文本框。在forms.py文件中,我将客户类从;
更改为;class CustomerSignUpForm(UserCreationForm):
first_name = forms.CharField(required=True)
last_name = forms.CharField(required=True)
email_address = forms.EmailField(required=True)
membership_tier = forms.CharField(required=True)
class Meta(UserCreationForm.Meta):
model = User
@transaction.atomic
def data_save(self):
user = super().save(commit=False)
user.first_name = self.cleaned_data.get('first_name')
user.last_name = self.cleaned_data.get('last_name')
user.is_customer = True
user.save()
customer = Customer.objects.create(user=user)
customer.email_address = self.cleaned_data.get('email_address')
customer.membership_tier = self.cleaned_data.get('membership_tier')
customer.save()
return user
到下面的
class CustomerSignUpForm(UserCreationForm):
member_tiers = (
'Basic',
'Intermediate',
'Beast'
)
first_name = forms.CharField(required=True)
last_name = forms.CharField(required=True)
email_address = forms.EmailField(required=True)
membership_tier = forms.CharField(choices = member_tiers, default = 'Basic', required=True)
class Meta(UserCreationForm.Meta):
model = User
@transaction.atomic
def data_save(self):
user = super().save(commit=False)
user.first_name = self.cleaned_data.get('first_name')
user.last_name = self.cleaned_data.get('last_name')
user.is_customer = True
user.save()
customer = Customer.objects.create(user=user)
customer.email_address = self.cleaned_data.get('email_address')
customer.membership_tier = self.cleaned_data.get('membership_tier')
customer.save()
return user
这是我的客户类在我的模型。py中如果有帮助的话,
class Customer(models.Model):
member_tiers = (
'Basic',
'Intermediate',
'Beast'
)
username = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
email_address = models.EmailField(max_length=30)
membership_tier = models.CharField(max_length = 30, choices = member_tiers, default = 'Basic')
我的问题归结为:我是否对我的forms.py文件进行了正确的更改,如果没有,我可以从中吸取什么教训,以便下次学习?
forms.CharField
没有choices
参数。请参阅此类型字段的文档。
你想要一个ChoiceField