I have a model registered in the admin site. One of its fields is a long string expression. I'd like to add custom form fields to the add/update page of this model in the admin that based on these fields values I will build the long string expression and save it in the relevant model field.
How can I do that?
UPDATE: Basically what I'm doing is building a mathematical or string expression from symbols, the user chooses symbols (these are the custom fields that are not part of the model) and when he clicks save then I create a string expression representation from the list of symbols and store it in the DB. I don't want the symbols are part of the model and DB, only the final expression.
If you absolutely only want to store the combined field on the model and not the two seperate fields, you could do something like this:
form
attribute on yourModelAdmin
(https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.form)save_formset
method on yourModelAdmin
(https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.save_model)I never done something like this so I'm not completely sure how it will work out.
Django 2.1.1 The primary answer got me halfway to answering my question. It did not help me save the result to a field in my actual model. In my case I wanted a textfield that a user could enter data into, then when a save occurred the data would be processed and the result put into a field in the model and saved. While the original answer showed how to get the value from the extra field, it did not show how to save it back to the model at least in Django 2.1.1
This takes the value from an unbound custom field, processes, and saves it into my real description field:
you can always create new admin template , and do what you need in your admin_view (override the admin add url to your admin_view):
Either in your admin.py or in a separate forms.py you can add a ModelForm class and then declare your extra fields inside that as you normally would. I've also given an example of how you might use these values in form.save():
To have the extra fields appearing in the admin just:
Like this:
UPDATE: In django 1.8 you need to add
fields = '__all__'
to the metaclass of YourModelForm.It it possible to do in the admin, but there is not a very straightforward way to it. Also, I would like to advice to keep most business logic in your models, so you won't be dependent on the Django Admin.
Maybe it would be easier (and maybe even better) if you have the two seperate fields on your model. Then add a method on your model that combines them.
For example:
Then in the admin you can add the
combined_fields()
as a readonly field:If you want to store the
combined_fields
in the database you could also save it when you save the model: