如何将外键合并到Django表单中?

时间:2019-07-03 13:49:38

标签: python django forms model

是否可以将外键合并到Django表单中,或将小部件合并到Django模型中?

我正在使用Django 2.2.2,并创建了一个模型(加速器)。我还创建了一个表单(审阅)。我已经使用Django表单创建了Review,因为我需要使用小部件来确保某些字段显示为单选按钮,并且我知道小部件不能在模型中使用。

但是,我还需要一个Review表单字段作为链接到Accelerator模型的外键,但是我的终端刚刚告诉我这是Django表单没有的属性。

如何创建可以同时使用小部件和外键的模型或表单?最终,我需要Accelerators模型可以通过另一个外键从“审阅”表单继承一个值。

class Accelerator(models.Model):
    name = models.CharField(max_length=100)
    summary = models.TextField()
    overall_rating = models.DecimalField(decimal_places=2, max_digits=3)
    author = models.ForeignKey(User, on_delete=models.CASCADE, default='admin')
    logo = models.ImageField(default='default.jpg', upload_to='logos')

    def __str__(self):
        return self.name

RATINGS = ['1', '2', '3', '4', '5']

class Review(forms.Form):
    subject = forms.ForeignKey(Accelerator, on_delete=models.CASCADE, blank=False)
    author = forms.ForeignKey(User, on_delete=models.CASCADE, blank=False)
    feedback = forms.TextField(blank=False)
    date_posted = forms.DateTimeField(default=timezone.now)
    mentorship = forms.ChoiceField(widget=forms.RadioSelect(choices=RATINGS))
    hiring = forms.ChoiceField(widget=forms.RadioSelect(choices=RATINGS))
    community = forms.ChoiceField(widget=forms.RadioSelect(choices=RATINGS))
    fundraising = forms.ChoiceField(widget=forms.RadioSelect(choices=RATINGS))
    corporate_dev = forms.ChoiceField(widget=forms.RadioSelect(choices=RATINGS))

1 个答案:

答案 0 :(得分:0)

使用ModelChoiceField

field = forms.ModelChoiceField(queryset=YourModel.objects.all())

就您而言,

subject = forms.ModelChoiceField(queryset=Accelerator.objects.all())
author = forms.ModelChoiceField(queryset=User.objects.all())