How to do dynamic form validation of django?

I have a form that should have either a valid url or a valid file to upload:

class ResourceUpload(ModelForm): ... uploadedfile = forms.FileField('file') url_address = forms.URLField('url') ... 

How can I redefine the FileField and URLField validators so that Django will only URLField error if both of the above fields are invalid, but with the exception that one of them is invalid if the other is valid?

+4
source share
4 answers

You need to set them as required=False , so the database database does not need to be filled out, and then use the form cleanup :

 import forms class ResourceUpload(ModelForm): ... uploadedfile = forms.FileField(required = False, upload_to='put/files/here') url_address = forms.URLField(required = False) ... def clean(self): cleaned_data = self.cleaned_data uploadedfile = cleaned_data.get("uploadedfile ") url_address = cleaned_data.get("url_address ") if not uploadedfile and mot url_address : raise forms.ValidationError("Provide a valid file or a valid URL.") return cleaned_data 
+7
source

my decision
pros: it saves an asterisk for the really required field and default error messages

 class Form(forms.ModelForm): field1 = SelectField field2 = ... field3 = ... def __init__(self, *args, **kwargs): super(Form, self).__init__(*args, **kwargs) if kwargs['data']: if kwargs['data'].get('field1') == '1': self.fields['field2'].required = True self.fields['field3'].required = False elif kwargs['data'].get('field1') == '2': self.fields['field2'].required = False self.fields['field3'].required = True 
+7
source

Here is my solution that really works ... (verified)

 def __init__(self, *args, **kwargs): super(YourForm, self).__init__(*args, **kwargs) if self.data and self.data.get('field_name') != 'SOMETHING': self.fields.get('field_name2').required = True 

This makes field_name2 required field if input field_name not 'SOMETHING' . Rocks Django!

+4
source

You should take a look at this django-dynamic-model-validation package

 from django.db import models from dynamic_validator import ModelFieldRequiredMixin class MyModel(ModelFieldRequiredMixin, models.Model): uploadedfile = models.FileField(upload_to='upload/path', blank=True, default='') url_address = models.URLField(blank=True, default='') REQUIRED_TOGGLE_FIELDS = ['uploadedfile', 'url_address'] 

This will confirm that only one of the fields can be provided, causing a validation error if both are used.

0
source

Source: https://habr.com/ru/post/1311851/


All Articles