Last active
May 5, 2020 02:38
-
-
Save mbrochh/8be2981cd0a54c3edf49ee2141f3f3c9 to your computer and use it in GitHub Desktop.
Validating a Django model instance with a model form without having a form data dict
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
# We have many instances in our apps where the user goes through many steps of forms. | |
# Each step obviously has it's own ModelForm. At the end, there is usually a final step | |
# for the user to submit everything. For this step, we usually want to run all the other | |
# form validations again, just to be sure that all the data looks good. | |
# Problem: How do you run a form validation if you don't have any POST/GET data? | |
class Form1(forms.ModelForm): | |
class Meta: | |
model = Model1 | |
fields = ['field1', 'field2'] | |
# Given this form, on my final submit view, I would want to do something like this: | |
def submit_view(request): | |
instance_id = request.POST.get('instance_id') | |
instance = Model1.objects.get(pk=instance_id) | |
form = Form1(data=???????????) | |
# See the problem? What is data? I can't pass the model instance as data | |
# POSSIBLE SOLUTION: | |
# So I thought, why not build up the data dict with three m ore lines of code: | |
def submit_view(request): | |
instance_id = request.POST.get('instance_id') | |
instance = Model1.objects.get(pk=instance_id) | |
data = {} | |
for field in Form1.Meta.fields: | |
data[field] = getattr(instance, field) | |
form = Form1(data=data) | |
if not form.is_valid(): | |
# tadaaa :) | |
# repeat the above for all other forms in the wizard | |
# Am I missing something here? Is this an antipattern? | |
# I can imagine some cases where this might fail, but I | |
# suspect that in most cases it would work? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment