可以为外键创建下拉列表吗?

时间:2014-09-24 10:52:27

标签: django

可以为类Task()开发人员字段创建下拉列表,这是一个外键吗?什么是创建它的最佳方式?

开发者models.py 来自django.db导入模型

class Developer(models.Model):
    name = models.CharField(max_length=21, null=False, blank=False)
    created = models.DateTimeField(auto_now_add=True)

    def __unicode__(self):
        return str(self.name)

models.py

from django.db import models

from developers.models import Developer

class Task(models.Model):
    story = models.ForeignKey(Story)
    developer = models.ForeignKey(Developer)
    description = models.CharField(max_length=360)
    iteration = models.IntegerField()
    created = models.DateTimeField(auto_now_add=True, auto_now=False)

forms.py

class AddTask(forms.ModelForm):
    story = forms.ForeignKey(Story)
    developer = forms.ForeignKey(Developer)
    description = forms.CharField(max_length=360)
    iteration = forms.IntegerField()

    class Meta:
        fields = ["name", "developer", "description", "iteration"]
        model = Task

2 个答案:

答案 0 :(得分:0)

如果您为ModelForm模型创建Developer,则每个外键都会呈现为ModelChoiceField。该字段的小部件是您要查找的html选择。

from django.forms import ModelForm

class DeveloperForm(ModelForm):
    class Meta:
        model Developer

看看at the docs以便更好地掌握它。

答案 1 :(得分:0)

我解决了。

我只需要使用forms.ModelChoiceField()。

class AddTaskForm(forms.ModelForm):
    story = forms.ModelChoiceField(Story.objects.all())
    developer = forms.ModelChoiceField(Developer.objects.all())
    description = forms.CharField(max_length=360)
    iteration = forms.IntegerField()

    class Meta:
        fields = ["story", "developer", "description", "iteration"]
        model = Task