Created
February 8, 2017 09:53
-
-
Save bmispelon/34f1c54b5ad28f0105638a22f9715959 to your computer and use it in GitHub Desktop.
A Django gCBV mixin that validates unboung (GET) forms
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def _initial_to_data(form): | |
""" | |
Given a form, convert its initial data into a dict that can simulate | |
the request.POST that would be generated if that form was submitted as-is. | |
This will respect the form's prefix and will convert all field values to | |
strings. | |
""" | |
return {f.html_name: f.value() for f in form} | |
class PreValidateFormMixin(object): | |
""" | |
Performs validation on unbound forms using their initial data. | |
""" | |
def get_form(self, *args, **kwargs): | |
form = super(PreValidateFormMixin, self).get_form(*args, **kwargs) | |
if form.is_bound: | |
return form | |
kwargs = self.get_form_kwargs() | |
kwargs['data'] = _initial_to_data(form) | |
form_copy = form.__class__(**kwargs) | |
if form_copy.is_valid(): | |
return form | |
else: | |
return form_copy |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment