且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使 django 中的 FileField 可选?

更新时间:2023-01-24 16:33:35

如果您在 forms.Form 派生类中使用 forms.FileField(),你可以设置:

If you're using a forms.FileField() in a forms.Form derived class, you can set:

class form(forms.Form):
    file = forms.FileField(required=False)

如果您使用的是 models.FileField() 并且为该模型分配了 forms.ModelForm,则可以使用

If you're using a models.FileField() and have a forms.ModelForm assigned to that model, you can use

class amodel(models.Model):
    file = models.FileField(blank=True, null=True)

您使用哪种取决于您如何派生表单以及您是否使用底层 ORM(即模型).

Which you use depends on how you are deriving the form and if you are using the underlying ORM (i.e. a model).