开发者

How to make FileField in django optional?

开发者 https://www.devze.com 2023-03-04 20:40 出处:网络
I have form with a textbox and filefield 开发者_StackOverflow社区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

I have form with a textbox and filefield 开发者_StackOverflow社区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?


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).


if you want to do this before the user submits the form you will need to do so using javascript(jquery, mootools, etc all offer some quick methods for that)

on the django side you could do so in a clean method in the form. This should get you started and you will need to display those validation errors on your template for the user to see them. The name of the clean method must match the form field name with "clean_" prepended.

def clean_textBoxFieldName(self):
  textInput = self.cleaned_data.get('textBoxFieldName')
  fileInput = self.cleaned_data.get('fileFieldName')

  if not textInput and not fileInput:
    raise ValidationError("You must use the file input box if not entering the full path.")
  return textInput  

def clean_fileFieldName(self):
  fileInput = self.cleaned_data.get('fileFieldName')
  textInput = self.cleaned_data.get('textBoxFieldName')
  if not fileInput and not textInput:
    raise ValidationError("You must provide the file input if not entering the full path")
  return fileInput

on the template

{% if form.errors %}
  {{form.non_field_errors}}
  {% if not form.non_field_errors %}
    {{form.errors}}
  {% endif %}
{% endif %}
0

精彩评论

暂无评论...
验证码 换一张
取 消