Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This is the solution I came up with. Requires subclassing ModelForm and BaseFormsetInline</p> <pre><code>class BrandBaseFormSet(BaseInlineFormSet): def save_new(self, form, commit=True): import ipdb;ipdb.set_trace() if form.cleaned_data['reassign_existing'] \ and form.cleaned_data['confirm_reassign'] \ and not form.instance.pk: return form.cleaned_data['reassign_existing'] else: import ipdb;ipdb.set_trace() return super(BrandBaseFormSet, self).save_new(form, commit=commit) class BrandAdminForm(forms.ModelForm): """ Allow for reassigning of reverse fk relationships inline of the child. """ reassign_existing = AutoCompleteSelectField('brand', required=False) confirm_reassign = BooleanField(required=False) def __init__(self, *args, **kwargs): super(BrandAdminForm, self).__init__(*args, **kwargs) self.fields['name'].required = False def clean(self): """ Here we check if its a new form or reassigning an existing brand. If its reassigning, we just do that in this method. :return: cleaned form data """ cleaned_data = super(BrandAdminForm, self).clean() if cleaned_data['reassign_existing'] \ and cleaned_data['confirm_reassign'] \ and not self.instance.pk: cleaned_data['reassign_existing'].company = self.instance.company cleaned_data['reassign_existing'].save() return cleaned_data elif cleaned_data['reassign_existing'] \ and cleaned_data['confirm_reassign'] \ and self.instance.pk: raise forms.ValidationError("You can't reassign AND add/edit a brand in the same form. Clear one of the sections.") else: if not cleaned_data['name']: msg = u"You must add a name to a new brand." self._errors["name"] = self.error_class([msg]) return cleaned_data def save(self, *args, **kwargs): if not self.cleaned_data['reassign_existing']: return super(BrandAdminForm, self).save(*args, **kwargs) else: return self.cleaned_data['reassign_existing'] class Meta: model = Brand </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload