ClementFilou
ClementFilou

Reputation: 1

Django ModelAdmin: update field without saving

I have an admin page that looks like this:

class NameAdmin(admin.ModelAdmin):
  list_display = ['long_name', 'short_name']
  search_fields = ['long_name','short_name']

In my admin page I have created a button (it is called "getname"), which after being pressed, should update the short_name field (if it's empty, otherwise leave it). However, the inserted text SHOULD NOT be saved to the database, only shown.

If the user agrees with the text, only then should he press "Save" and then it should be saved to the database.

the save_model method does of course not work, as it saves it to the database.

def save_model(self, request, obj, form, change):
  if 'getshortname' in request.POST:
    if not obj.short_name:
       obj.short_name = model_support.parse_shortname(obj.long_name)

Any ideas?

Many thanks

Upvotes: -1

Views: 1365

Answers (1)

raratiru
raratiru

Reputation: 9636

I would create a form in forms.py:

from django import forms
from myapp.models import MyModel

class MyModelForm(forms.ModelForm):
    update_me = forms.CharField(max_length=100, required=False)

    class Meta(Object):
        model = MyModel

Then in admin.py:

from django.contrib import admin
from myapp.forms import MyModelForm


class MyModelAdmin(admin.ModelAdmin):
    form = MyModelForm


admin.site.register(MyModel, MyModelAdmin)

This way, you have a field in the model that will not be saved to the database, is not required, you can update it and using the save_model method you can pass the value to the relevant field of your model in order to be saved to the database.

Upvotes: 0

Related Questions