A.Raouf
A.Raouf

Reputation: 2320

Database choices with modelchoiceform connection

Now I have a model field with choices like that models.py

class Person(models.Model):
    user = 'US'
    training_center = 'TC'
    instructor = 'IN'
    USER_TYPE_CHOICES = (
        (training_center, 'Training center'),
        (instructor, 'Instructor'),
        (user, 'User'),
    )
    user_type = models.CharField(max_length=2, choices=USER_TYPE_CHOICES, default=user)

forms.py

class RegistrationForm(forms.Form):
     Type = forms.ModelChoiceField(
             widget=forms.RadioSelect(
                 attrs=dict(required=True,
                            render_value=False)
             ),
             queryset=Person.objects.values('user_type')
         )

Now I have this model and this form , I want a radio button appears with choices in the model: training center , instructor,user, How can I make the choices get the values from database, and if there is another way to make it, can you mention it and help me

Upvotes: 0

Views: 39

Answers (1)

v1k45
v1k45

Reputation: 8250

If you just want the choices defined in your Person model to appear in your RegistrationForm, you can do it without ModelChoiceField.

Use ChoiceField with Person model choices.

In your forms.py:

class RegistrationForm(forms.Form):
     user_type = forms.ChoiceField(choices=Person.USER_TYPE_CHOICES)

Upvotes: 1

Related Questions