Django表单:设置初始值

时间:2017-04-04 11:43:01

标签: python django

我有一个表单,试图注册目前正在进行的工作'项目到一个部门。

models.py

class Department(models.Model):
    dept_name = models.CharField(max_length=25)
    address = models.CharField(max_length=50)

class Project(models.Model):
    projectname = models.CharField(max_length=25)
    department = models.ForeignKey(Department, null=True, blank=True, on_delete=models.SET_NULL)

forms.py

class ProjectChoiceField(ModelChoiceField): # return a list of projects for the department form.
    def label_from_instance(self, obj):
        return "%s" % obj.projectname

class SetDepartmentProjectForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(SetDepartmentProjectForm, self).__init__(*args, **kwargs)
        if not self.fields['projectstring']: # no default set
            self.fields['projectstring'] = ProjectChoiceField(Project.objects.filter(department=self.instance), required=False)
        else:
            project = Project.objects.get(projectname=self.fields['projectstring'])
            self.fields['projectstring'] = ProjectChoiceField(Project.objects.filter(department=self.instance), required=False, initial=project.pk)

    class Meta:
        model = Department
        fields = ['dept_name', 'address', 'projectstring']

如果没有设置值,这适用于创建下拉项目集,但是当它设置为某个项目名称值时 - 初始arg(Project.pk)不会选择正确的项目作为初始值形式。

1 个答案:

答案 0 :(得分:-1)

您可以通过设置initial=self.instance.related_fieldname.pk

来实现