ModelChoiceField 不显示外键选择

use*_*150 8 python django django-models django-forms

我想在 Django 表单中显示一个下拉列表,其中下拉项目在另一个应用程序的另一个模型中指定。这就是我的意思:

标题/模型.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
Run Code Online (Sandbox Code Playgroud)

用户/模型.py

class User(models.Model):
    ...
    user_title = models.ForeignKey('title.Title', on_delete=models.CASCADE)
    ...
Run Code Online (Sandbox Code Playgroud)

用户/表单.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()
Run Code Online (Sandbox Code Playgroud)

使用上面的代码,下拉字段正确呈现;然而,它是空的。 在此处输入图片说明

任何想法或建议都非常感谢。

谢谢。

Riy*_* Ac 5

请将您的 user_title 字段更改为此并尝试此操作。

user_title = forms.ModelChoiceField(queryset=Title.objects.all(), widget=forms.Select(attrs={'class': 'form-control'}))
Run Code Online (Sandbox Code Playgroud)