Manas Chaturvedi
Manas Chaturvedi

Reputation: 5540

Django: 'module' object has no attribute 'ChoiceField', 'MultipleChoiceField'

I'm trying to create radio buttons and checkboxes into my forms, and am trying to use the model fields ChoiceField and MultipleChoiceField respectively for the same.

forms.py

from django import forms
from rango.models import Evangelized

class EvangelizedForm(forms.ModelForm):
    gender = forms.ChoiceField(widget=forms.RadioSelect(
                 choices=Evangelized.GENDER_CHOICES), help_text="Gender")
    area_of_interest = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple(
                                                    choices=Evangelized.AREA_CHOICES), help_text="Areas of interest(Upto 3)")

models.py

from django.db import models

class Evangelized(models.Model):
    GENDER_CHOICES = (('M', 'Male'), ('F', 'Female'), ('U', 'Unisex/Parody'))
    gender = models.ChoiceField(choices=GENDER_CHOICES)
    AREA_CHOICES = (('Govt', 'Govt'), ('Entertainment', 'Entertainment'), ('Automobile', 'Automobile'),
                        ('Careers', 'Careers'), ('Books', 'Books'), ('Family', 'Family'), ('Food', 'Food'),
                            ('Gaming', 'Gaming'), ('Beauty', 'Beauty'), ('Sports', 'Sports'), ('Events', 'Events'),
                                ('Business', 'Business'), ('Travel', 'Travel'), ('Health', 'Health'), ('Technology','Technology'))
    area_of_interest = models.MultipleChoiceField(choices=AREA_CHOICES)

However, I'm getting the following errors while working with each type of model field respectively:

 'module' object has no attribute 'ChoiceField'



'module' object has no attribute 'MultipleChoiceField'

What seems to be wrong with my code?

Upvotes: 2

Views: 12043

Answers (2)

Hunter_71
Hunter_71

Reputation: 789

You should use models.CharField instead :-) see documentation

gender = models.CharField(max_length=1, choices=GENDER_CHOICES)

Upvotes: 3

Alvaro
Alvaro

Reputation: 12037

The models define database level types.

You must specify the data type of the model and you can specify the choices with the "choices" kwarg.

So, your models should look like this:

from django.db import models

class Evangelized(models.Model):
    GENDER_CHOICES = (('M', 'Male'), ('F', 'Female'), ('U', 'Unisex/Parody'))
    gender = models.CharField(max_length=1, choices=GENDER_CHOICES)

For the case of the multiple choice field you can use a CommaSeparatedIntegerField.

I suggest you take a look at the docs for models with choices

Upvotes: 5

Related Questions