I have the following model and i am using 'save_as' in admin.py to enable a “save as new” feature on admin change forms.
The goal is that if i use 'save_as' the "old" object should have set the boolean field 'hide' to True.
I tried to implement the ModelAdmin method 'save_model' to admin.py but this only changes the value for the "new" object.
Is it possible to change the "old" object also?
models.py
class Person(models.Model):
name = models.CharField(max_length=64)
hide = models.BooleanField(default=0)
admin.py
class personAdmin(admin.ModelAdmin):
save_as = True
def save_model(self, request, obj, form, change):
obj.hide = True
super(personAdmin, self).save_model(request, obj, form, change)
Try this:
def save_model(self, request, obj, form, change):
# Get old object's id from the url
old_obj_id = resolve(request.path).args[0]
# Now that we know the id, we can easily fetch it from database
old_obj = Person.objects.get(id=old_obj_id)
# Update it's hide field
old_obj.hide = True
# Don't forget to save it!
old_obj.save()
# Now we can save the new object as a new one (save_as)
super(personAdmin, self).save_model(request, obj, form, change)
Related
I have a signal inside my django app where I would like to check if a certain field in my model has been updated, so I can then proceed and do something.
My model looks like this...
class Product(models.Model):
name = models.CharField(max_length=100)
price = models.PositiveIntegerField()
tax_rate = models.PositiveIntegerField()
display_price = models.PositiveInteger()
inputed_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.SET_NULL)
updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.SET_NULL)
My signal looks like this...
#receiver(post_save, sender=Product)
def update_model(sender, **kwargs):
instance = kwargs['instance']
if 'tax_rate' in kwargs['update_fields']:
# do something
This returns the error None is not an iterable. I have read the django signal documentation regarding the update_fields and it says The set of fields to update as passed to Model.save(), or None if update_fields wasn’t passed to save().
I should mention that I am working inside django admin here so what I hoped would happen is, I could create an instance of my Product model in django admin and then later if the value of tax_rate or price were updated, I could check for those and update the list_price accordingly. However, kwargs['update_fields'] always returns None.
What am I getting wrong? Or is there some other way I could achieve that result inside django admin?
Updated section
Now, say I introduce a field called inputed_by in my product model, that points to the user model and I want that field populated when the model is first saved. Then another field updated_by that stores the user who last updated the model. At the same time I wish to check whether either or both the tax_rate or price has been updated.
Inside my model admin I have the following method...
def save_model(self, request, obj, form, change):
update_fields = []
if not obj.pk:
obj.inputed_by = request.user
elif change:
obj.updated_by = request.user
if form.initial['tax_rate'] != form.cleaned_data['tax_rate']:
update_fields.append('tax_rate')
if form.initial['price'] != form.cleaned_data['price']:
update_fields.append('price')
obj.save(update_fields=update_fields)
super().save_model(request, obj, form, change)
My signal now looks like this...
#receiver(post_save, sender=Product, dispatch_uid="update_display_price")
def update_display_price(sender, **kwargs):
created = kwargs['created']
instance = kwargs['instance']
updated = kwargs['update_fields']
checklist = ['tax_rate', 'price']
# Prints out the frozenset containing the updated fields and then below that `The update_fields is None`
print(f'The update_fields is {updated}')
if created:
instance.display_price = instance.price+instance.tax_rate
instance.save()
elif set(checklist).issubset(updated):
instance.display_price = instance.price+instance.tax_rate
instance.save()
I get the error 'NoneType' object is not iterable
The error seems to come from the line set(checklist).issubset(updated). I've tried running that line specifically inside the python shell and it yields the desired results. What's wrong this time?
The set of fields should be passed to Model.save() to make them available in update_fields.
Like this
model.save(update_fields=['tax_rate'])
If you are creating something from django admin and getting always None it means that update_fields has not been passed to model's save method. And because of that it will always be None.
If you check ModelAdmin class and save_model method you'll see that call happens without update_fields keyword argument.
It will work if you write your own save_model.
The code below will solve your problem:
class ProductAdmin(admin.ModelAdmin):
...
def save_model(self, request, obj, form, change):
update_fields = []
# True if something changed in model
# Note that change is False at the very first time
if change:
if form.initial['tax_rate'] != form.cleaned_data['tax_rate']:
update_fields.append('tax_rate')
obj.save(update_fields=update_fields)
Now you'll be able to test memberships in update_model.
To add to Davit Tovmasyan's post. I made a more universal version that covers any field change using a for loop:
class ProductAdmin(admin.ModelAdmin):
...
def save_model(self, request, obj, form, change):
update_fields = []
for key, value in form.cleaned_data.items():
# True if something changed in model
if value != form.initial[key]:
update_fields.append(key)
obj.save(update_fields=update_fields)
EDIT: WARNING This isnt actually a full solution. Doesnt seem to work for object creation, only changes. I will try to figure out the full solution soon.
I wanted to add an alternative that relies on the pre_save signal to get the previous version of the instance you're evaluating (from this SO answer):
#receiver(pre_save, sender=Product)
def pre_update_model(sender, **kwargs):
# check if the updated fields exist and if you're not creating a new object
if not kwargs['update_fields'] and kwargs['instance'].id:
# Save it so it can be used in post_save
kwargs['instance'].old = User.objects.get(id=kwargs['instance'].id)
#receiver(post_save, sender=Product)
def update_model(sender, **kwargs):
instance = kwargs['instance']
# Add updated_fields, from old instance, so the method logic remains unchanged
if not kwargs['update_fields'] and hasattr(instance, 'old'):
kwargs['update_fields'] = []
if (kwargs['update_fields'].instance.tax_rate !=
kwargs['update_fields'].instance.old.tax_rate):
kwargs['update_fields'].append('tax_rate')
if 'tax_rate' in kwargs['update_fields']:
comparing to the accepted answer
Disadvantages
Extra query on every save that doesn't have update_fields (if you're not opening Django Admin to the world, this shouldn't be problematic)
Advantages
Don't need to override any method or class
You only need to implement the logic for the fields you want to evaluate, and they are in the same method, so no excuse for mistakes ;)
If you're doing this for many classes, you should probably look at other solutions (but the accepted answer is also not perfect for that!)
You can do this.
def save_model(self, request, obj, form, change):
if change:
obj.save(update_fields=form.changed_data)
else:
super().save_model(request, obj, form, change)
I'm totally new in Python and Django :) and i need some help.
What i want to do:
I have a model Page and i need to add a custom field "message" when someone try to update one object.
Why? Because i'm building a revision system. This field, it's just an explanation about the change. So this field is not linked to the Page (but to another model PageRevision)
After some research i managed to add this field to my form in the admin.py file, like this:
class PageAdminForm(forms.ModelForm):
# custom field not backed by database
message = forms.CharField(required=False)
class Meta:
model = Page
it's working, my field is now displayed...But i don't want this field everywhere. Just when someone try to update a Page object.
i have found this answer different-fields-for-add-and-change-pages-in-admin but it's not working for me because it's a custom field (i think).
The rest of my code in admin.py:
class PageAdmin(admin.ModelAdmin):
form = PageAdminForm
fields = ["title", "weight", "description", "message"]
list_display = ["title", "weight", "description"]
list_filter = ["updated_at"]
def get_form(self, request, obj=None, **kwargs):
if obj is None:
# not working ?
kwargs['exclude'] = ['message']
# else:
# kwargs['exclude'] = ['message']
return super(PageAdmin, self).get_form(request, obj, **kwargs)
def save_model(self, request, obj, form, change):
if not obj.id:
obj.author = request.user
obj.modified_by = request.user
wiki_page = obj.save()
# save page in revision table
revision = PageRevision(change=change, obj=wiki_page,
request=request)
# retrieve value in the custom field
revision.message = form.cleaned_data['message']
revision.save()
def get_form doesn't exclude my custom message field because i think it doesn't know is existence. If i put another field like title, it's works.
So how to exclude the custom field from add view ?
Thanks :)
You're right, it won't work this way, because 'message' is not a field found on the Page model and the ModelAdmin class will ignore the exclusion. You can achieve this in many ways, but I think the best way to do it is this:
class PageAdmin(admin.ModelAmin):
change_form = PageAdminForm
...
def get_form(self, request, obj=None, **kwargs):
if obj is not None:
kwargs['form'] = self.change_form
return super(UserAdmin, self).get_form(request, obj, **defaults)
Basicaly here django will use an auto-generated ModelForm when adding a Page and your custom form when editing the Page. Django itself uses a similar technique to display different forms when adding and changing a User:
https://github.com/django/django/blob/stable/1.6.x/django/contrib/auth/admin.py (the interesting part is in line 68)
I just stumbled upon this same question and, since it comes in the first search results I would like to add this other solution for people that do not want to use a custom form.
You can override the get_fields method of your admin class to remove a custom field from the Add page.
def get_fields(self, request, obj=None):
fields = list(super().get_fields(request, obj=obj))
if obj is None:
fields.remove("message")
return fields
I need to process a file uploaded in a django admin form. I've added a file upload field to the form:
class ExampleInline(admin.TabularInline):
model = OtherExample
extra = 1
class ExampleForm(forms.ModelForm):
filedata = forms.FileField()
class Meta:
model = ExampleModel
class ExampleModelAdmin(admin.ModelAdmin):
form = ExampleForm
inlines = [ExampleInline,]
This renders the form exactly like I want it to render. The data returned in Request is exactly what I expect.
The issue is that I want to access the contents of the inline.
class ExampleAdmin(admin.ModelAdmin):
...
def save_model(self, Request, obj, form, change):
the_file = form.cleaned_data['filedata']
# do amazing things to contents of file
At this point I want to reference the results of what the user selected in the inline. Whatever they picked for OtherExample.
How do I access that through the form? I would prefer not to go through the Request but am willing to do that. I'm also willing to examine save_related(self,request, form, formset, change)
save_related can do this, although it's called after the form is saved so you'll end up saving the object twice. You can access the object as form.instance or formset.instance.
def save_related(self, request, form, formsets, change):
obj = form.instance
# whatever your formset dependent logic is to change obj.filedata
obj.save()
super(ExampleAdmin, self).save_related(request, form, formsets, change)
Is it possible to save the related objects before the actual object being edited on a django admin form?
For example:
in models.py
class Parent(model.Model):
pass
class Child(model.Model):
parent = models.ForeignKey(Parent)
#receiver(post_save,sender = Parent)
def notify_parent_save(sender, instance=None, **kwargs):
print "Parent save"
#receiver(post_save,sender = Child)
def notify_child_save(sender, instance=None, **kwargs):
print "Child saved"
in admin.py
class ChildInline(admin.TabularInline):
model = Child
extra = 1
class ParentsAdmin(admin.ModelAdmin):
inlines = [ChildInline]
admin.site.register(Parent,ParentsAdmin)
Now, in django admin if I save a parent object, it will output on the console.
Parent save
Child save
I need this to happen in revese order:
Child save
Parent save
The following will save the children first:
class ParentAdmin(admin.ModelAdmin):
inlines = [ChildInline]
def save_model(self, request, obj, form, change):
pass # don't actually save the parent instance
def save_formset(self, request, form, formset, change):
formset.save() # this will save the children
form.instance.save() # form.instance is the parent
I was having issues with the answers in this post, so I figured out a more concise answer. I was having an issue because using django-fsm, the other answers here would try to save the model multiple times (once for every formset) rather than once at the end.
def save_model(self, request, obj, form, change):
if not obj.pk: # call super method if object has no primary key
super(YourAdmin, self).save_model(request, obj, form, change)
else:
pass # don't actually save the parent instance
def save_related(self, request, form, formsets, change):
form.save_m2m()
for formset in formsets:
self.save_formset(request, form, formset, change=change)
super(YourAdmin, self).save_model(request, form.instance, form, change)
This essential just flips the order of save_model and save_related as called in Django ModelAdmin source
ccrisan's answer brought me on the right track, but I think there is a flaw regarding save behavior of instances that do not yet exist in the database. In this case it's not possible to save the related objects first, because there is no foreign key that they can point to. For me the following extension did the trick:
class ParentAdmin(admin.ModelAdmin):
inlines = [ChildInline]
def save_model(self, request, obj, form, change):
if not obj.pk: # call super method if object has no primary key
super(ParentAdmin, self).save_model(request, obj, form, change)
else:
pass # don't actually save the parent instance
def save_formset(self, request, form, formset, change):
formset.save() # this will save the children
form.instance.save() # form.instance is the parent
Depending on what you exactly want to do in your signals, can you just change the post_save to pre_save for the Child model ?
That question might look similar to this one, but it's not...
I have a model structure like :
class Customer(models.Model):
....
class CustomerCompany(models.Model):
customer = models.ForeignKey(Customer)
type = models.SmallIntegerField(....)
I am using InlineModels, and have two types of CustomerCompany.type. So I define two different inlines for the CustomerCompany and override InlineModelAdmin.queryset
class CustomerAdmin(admin.ModelAdmin):
inlines=[CustomerCompanyType1Inline, CustomerCompanyType2Inline]
class CustomerCompanyType1Inline(admin.TabularInline):
model = CustomerCompany
def queryset(self, request):
return super(CustomerCompanyType1Inline, self).queryset(request).filter(type=1)
class CustomerCompanyType2Inline(admin.TabularInline):
model = CustomerCompany
def queryset(self, request):
return super(CustomerCompanyType2Inline, self).queryset(request).filter(type=2)
All is nice and good up to here, but for adding new records for InlineModelAdmin, I still need to display type field of CustomerCompany on the AdminForm, since I can not override save method of an InlineModelAdmin like:
class CustomerCompanyType2Inline(admin.TabularInline):
model = CustomerCompany
def queryset(self, request):
return super(CustomerCompanyType2Inline, self).queryset(request).filter(type=2)
#Following override do not work
def save_model(self, request, obj, form, change):
obj.type=2
obj.save()
Using a signal is also not a solution since my signal sender will be the same Model, so I can not detect which InlineModelAdmin send it and what the type must be...
Is there a way that will let me set type field before save?
Alasdair's answer isn't wrong, but it has a few sore points that could cause problems. First, by looping through the formset using form as the variable name, you actually override the value passed into the method for form. It's not a huge deal, but since you can do the save without commit right from the formset, it's better to do it that way. Second, the all important formset.save_m2m() was left out of the answer. The actual Django docs recommend the following:
def save_formset(self, request, form, formset, change):
instances = formset.save(commit=False)
for instance in instances:
# Do something with `instance`
instance.save()
formset.save_m2m()
The problem you're going to run into is that the save_formset method must go on the parent ModelAdmin rather than the inlines, and from there, there's no way to know which inline is actually being utilized. If you have an obj with two "types" and all the fields are the same, then you should be using proxy models and you can actually override the save method of each to set the appropriate type automatically.
class CustomerCompanyType1(CustomerCompany):
class Meta:
proxy = True
def save(self, *args, **kwargs):
self.type = 1
super(CustomerCompanyType1, self).save(*args, **kwargs)
class CustomerCompanyType2(CustomerCompany):
class Meta:
proxy = True
def save(self, *args, **kwargs):
self.type = 2
super(CustomerCompanyType2, self).save(*args, **kwargs)
Then, you don't need to do anything special at all with your inlines. Just change your existing inline admin classes to use their appropriate proxy model, and everything will sort itself out.
There's a save_formset method which you could override. You'd have to work out which inline the formset represents somehow.
def save_formset(self, request, form, formset, change):
instances = formset.save(commit=False)
for instance in instances:
# Do something with `instance`
instance.save()
formset.save_m2m()
Other answers are right when it comes to using save_formset. They are missing a way to check what model is currently saved though. To do that, you can just:
if formset.model == CustomerCompany:
# actions for specific model
Which would make the save_formset function look like: (assuming you just want to override save for the specific model(s))
def save_formset(self, request, form, formset, change):
for obj in formset.deleted_objects:
obj.delete()
# if it's not the model we want to change
# just call the default function
if formset.model != CustomerCompany:
return super(CustomerAdmin, self).save_formset(request, form, formset, change)
# if it is, do our custom stuff
instances = formset.save(commit=False)
for instance in instances:
instance.type = 2
instance.save()
formset.save_m2m()
For the cases where you need to take an action if the registry is new, you need to do it before saving the formset.
def save_formset(self, request, form, formset, change):
for form in formset:
model = type(form.instance)
if change and hasattr(model, "created_by"):
# craeted_by will not appear in the form dictionary because
# is read_only, but we can anyway set it directly at the yet-
# to-be-saved instance.
form.instance.created_by = request.user
super().save_formset(request, form, formset, change)
In this case I'm also applying it when the model contains a "created_by" field (because this is for a mixin that I'm using in many places, not for a specific model).
Just remove the and hasattr(model, "created_by") part if you don't need it.
Some other properties that might be interesting for you when messing with formsets:
"""
The interesting fields to play with are:
for form in formset:
print("Instance str representation:", form.instance)
print("Instance dict:", form.instance.__dict__)
print("Initial for ID field:", form["id"].initial)
print("Has changed:", form.has_changed())
form["id"].initial will be None if it's a new entry.
"""
I hope my digging helps someone else! ^^