Home > Net >  How to solve "TypeError: Field.__init__() got an unexpected keyword argument 'choices'
How to solve "TypeError: Field.__init__() got an unexpected keyword argument 'choices'

Time:07-11

I recently decided to update my forms.py file of my Django project to make one of the fields into a drop down menu rather than an empty text box. In my forms.py file, I changed the class for customers from;

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

to the following

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

And here is my customer class in my models.py as well if that will help,

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

What my question boils down to is: Did I make the correct changes to my forms.py file and if not, what can I take away from this to learn for next time?

CodePudding user response:

forms.CharField does not have a choices argument. See the documentation about this type of field.

You want a ChoiceField

  • Related