Reputation: 950
Is it possible to update a field and when saving it, it should save other fields with new changes.
For example, I have the below model,
class Backup(models.Model):
user=models.ForeignKey(User)
title=models.CharField(max_length=200)
is_approve=models.BooleanField(default=False)
is_bad=models.BooleanField(default=False)
country=models.CharField(max_length=100)
Now, my main aim is to just make is_approve
field True
. My secondary aim is to update other fields alongside the is_approve
field, incase the user makes changes before clicking on the approve
button in template.
@staff_member_required
def activate_moderation(request, backup_id=None):
if id:
vpostmod=get_object_or_404(Backup, id=backup_id)
vpostmod.is_approve =1
vpostmod.save()
How can I plug in instances of all fields alongside with the save(), in order to make the changes after setting is_approve
to True.
UPDATE TO DANIEL'S QUESTION
The model has a 'Backup' ModelForm. The forms are rendered via Django admin (BackupAdmin) using the same 'backup' modelform.
I passed my button link by invoking the change_form place in my admin/app_name/modelname/ folder.
def render_change_form(self, request, context, *args, **kwargs):
backup= self.get_object(request, self.backup_id)
context.update({'backup':backup})
return super(BackupAdmin, self).render_change_form(request, context, *args, **kwargs)
And the change form template is like this:
{% block submit_buttons_bottom %}
<div class="submit-row">
{% if backup.is_approve %}
<p>pass</p>
{% else %}
<a href="{% url 'activate_moderation' backup.id %}" class="historylink"> <input type="button" value="{% trans 'Approve' %}" name="_approvebutton" /></a>
<input type="button" value="{% trans 'Reject' %}" name="_rejectbutton" />
{% endif %}
</div>
{{ block.super }}
{% endblock %}
Upvotes: 0
Views: 314
Reputation: 51715
Do you have several options.
First one is to overwrite save method on Backup model:
#Backup
def save(self, *args, **kwargs):
if self.pk:
previous_Backup = Backup.objects.get(self.pk).is_approve
super(Backup, self).save(*args, **kwargs)
if self.pk and self.is_approve != previous_Backup:
#make changes
Second one is binding function to post save signal + django model utils field tracker:
@receiver(post_save, sender=Backup)
def create_change_backup(sender,instance, signal, created, **kwargs):
if created:
previous_Backup = get it from django model utils field tracker
#make changes
Upvotes: 1