django - ModelForm won't validate because missing field is assigned in clean() -


i have modelform custom save method populate model field kwarg url params (that passed form):

from app.models import mymodel class mymodelform(forms.modelform):     def __init__(self, *args, **kwargs):         self.fk_customer = kwargs.pop('customer')         super(mymodelform, self).__init__(*args, **kwargs)      class meta:         model = mymodel         fields = '__all__'      def clean(self):         cleaned_data = super(mymodelform, self).clean()         cleaned_data['fk_customer'] = self.fk_customer         return cleaned_data 

when inspect cleaned_data in view, fk_customer present , valid. is_valid() false, , modelform won't save(). if override few things , force save, field fk_customer saved none.

what's going on , how can alter cleaned_data , still validate?

if not displaying customer field form, should exclude form class instead of using __all__.

then, try set customer in form's save method instead of clean method. following untested:

class mymodelform(forms.modelform):     def __init__(self, *args, **kwargs):         self.customer = kwargs.pop('customer')         super(mymodelform, self).__init__(*args, **kwargs)      class meta:         model = mymodel         exclude = ('customer',)       def save(self, commit=true)         instance = super(mymodelform, self).save(commit=false)         instance.customer = self.customer         if commit:             instance.save()             self.save_m2m()         return instance 

Comments

Popular posts from this blog

python - Operations inside variables -

Generic Map Parameter java -

arrays - What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it? -