Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ModelChoiceField does not show ForeignKey choices

I want to show a dropdown in Django Form where the dropdown items are specified in another model in another app. Here's what I mean:

title/models.py

TITLE_CHOICES = (
    ('MR', 'Mr'),
    ('MS', 'Ms'),
    ('MISS', 'Miss'),
    ('MRS', 'Mrs'),
    ('MX', 'Mx'),
)

class Title(models.Model):
    title_name = models.CharField(max_length=10, choices=TITLE_CHOICES)

    def __str__(self):
        return self.title_name

user/models.py

class User(models.Model):
    ...
    user_title = models.ForeignKey('title.Title', on_delete=models.CASCADE)
    ...

user/forms.py

class SignupForm(forms.ModelForm):
        user_title = forms.ModelChoiceField(queryset=Title.objects.all())

        class Meta:
            model = User
            fields = '__all__'

        def signup(self, request, user): #this is to override the **allauth** signup form
            user.user_title = self.cleaned_data['title_name']
            ...
            ...

            user.save()

With the above code, the dropdown field renders properly; however, it is empty. enter image description here

Any ideas or suggestions are greatly appreciated.

Thanks.

like image 524
user2771150 Avatar asked Aug 06 '20 07:08

user2771150


1 Answers

Please change your user_title field to this and Try this.

user_title = forms.ModelChoiceField(queryset=Title.objects.all(), widget=forms.Select(attrs={'class': 'form-control'}))
like image 146
Riyas Ac Avatar answered Sep 21 '22 00:09

Riyas Ac