我想在 Django 表单中显示一个下拉列表,其中下拉项目是在另一个应用程序的另一个模型中指定的。这就是我的意思:
标题/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
用户/模型.py class User(models.Model):
...
user_title = models.ForeignKey('title.Title', on_delete=models.CASCADE)
...
用户/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()
使用上面的代码,下拉字段正确呈现;然而,它是空的。任何想法或建议都非常感谢。
谢谢。
最佳答案
请将您的 user_title 字段更改为此并尝试此操作。
user_title = forms.ModelChoiceField(queryset=Title.objects.all(), widget=forms.Select(attrs={'class': 'form-control'}))
关于python - ModelChoiceField 不显示外键选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63278670/