DjangoModelForm:如何添加额外的字段并在发送到视图之前对其进行预处理

DjangoModelForm: How to add extra fields and preprocess them before sending to views

我有一个显示所有字段的模型表单:

class BatchForm(ModelForm):

    class Meta:
        model = Batch
        fields = ('__all__')

它工作正常并显示了视图中的所有字段。 我现在想向此表单添加模型中不存在的额外字段。 这些字段是:

completed_tasks: int
statistics: array

然后我想在表单中添加 2 个方法,这些方法在将其发送到视图之前自动填充这些字段。这些方法将是:

def completed_tasks_method(self, obj):
    return obj.assignments_per_task * obj.total_tasks()

def statistics_method(self, obj):
    #something

我不知道如何扩展模型以添加额外的属性,然后如何在将字段发送到视图之前填充字段。 你能帮忙吗?谢谢

您可以在模型中添加字段并操作为其提供初始值。

class BatchForm(ModelForm):
    completed_tasks = forms.IntegerField()
    statistics = forms.MultipleChoiceField()
    # or whateer fields you want to use
    class Meta:
        model = Batch
        fields = ('__all__')

观看次数

form = BatchForm(initial={'completed_tasks', <VALUE>, 'statistics': <VALUE>})

或者如果你想用方法来做,你可以做

class BatchForm(ModelForm):
    completed_tasks = forms.IntegerField()
    statistics = forms.MultipleChoiceField()
    # or whateer fields you want to use
    class Meta:
        model = Batch
        fields = ('__all__')

    def __init__(self, *args, **kwargs):
        super(BatchForm, self).__init__(*args, **kwargs)
        if self.instance:
            self.initial['completed_tasks'] = self.completed_tasks_method(self.instance)
            self.initial['statistics'] = self.statistics_method(self.instance)

    def completed_tasks_method(self, obj):
        return obj.assignments_per_task * obj.total_tasks()

    def statistics_method(self, obj):
        # something