如何使 django 中的 FileField 可选? [英] How to make FileField in django optional?

查看:37
本文介绍了如何使 django 中的 FileField 可选?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Django 中有一个带有文本框和文件字段的表单.它应该让用户将文本粘贴到该框中或上传文件.如果用户已将文本粘贴到框中,则无需检查 fileField.

I have form with a textbox and filefield in django. It should let the use either paste the text into that box or upload a file. If the user has pasted the text into the box, I needn't check the fileField.

如何使 forms.FileField() 成为可选的?

How do I make the forms.FileField() optional?

推荐答案

如果您在 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).

这篇关于如何使 django 中的 FileField 可选?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆