Django admin overriding storing method in strings?

Is there a way to override the save method for the inline form and the parent at the same time?

I would like to change the value of the field when the user saves the edited inline form.

Thanks:)

+7
django django-admin
source share
2 answers

You can override FormSet to set up storing inline strings.

class SomeInlineFormSet(BaseInlineFormSet): def save_new(self, form, commit=True): return super(SomeInlineFormSet, self).save_new(form, commit=commit) def save_existing(self, form, instance, commit=True): return form.save(commit=commit) class SomeInline(admin.StackedInline): formset = SomeInlineFormSet # .... 

Please note that save_new() uses only the form to receive data, it does not allow ModelForm transmit data. Instead, he builds the model itself. This allows you to insert a parental relationship, since they do not exist in the form. Therefore, overriding form.save() does not work.

For common inline strings, the form.save() method is never called, and form.cleaned_data used instead to get all the values, and Field.save_form_data() used to store the values ​​in the model instance.


FYI, some general advice to understand what it is; it is really valuable to have an IDE (or perhaps a vim or Sublime setup configuration) that makes it easy to get to symbolic definitions. The above code was computed by entering inline / formet code and seeing what happens. In the case of PyCharm, which works by holding Command (or Ctrl) and clicking on a character. If you are a vim user, ctags can do something similar for you.

+9
source share

One way is to connect the model pre_save to your built-in signal:

 from django.db.models.signals import pre_save from your_app.models import YourModel def callback(sender, **kwargs): # 'instance' is the model instance that is about to be saved, # so you can do whatever you want to it. instance.field = new_value pre_save.connect(callback, sender=YourModel) 

But I'm not sure why you cannot just override the save method, which is almost always the best approach.

+2
source share

All Articles