How to make FileField in django optional?

Question:

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?

Asked By: tamizhgeek

||

Answers:

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

Answered By: user257111

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 %}
Answered By: grantk
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.