Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
459 views
in Technique[技术] by (71.8m points)

python - How to make FileField in django optional?

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

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)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...