简体   繁体   中英

Saving the current data before updating the form in Django

I would like to create a history of changes in one of my models. That every time I will update it, the current data will be saved to a different table and at the same time, the new data enters to another table. How will I be able to do that? I saw examples and they are based from the admin. But I still don't get the idea of it. This maybe a noob question but I'm still learning Django.

models.py

class tblTicket(models.Model): #new data will be entered here
    remarks = models.TextField("Action Taken", max_length=500,default='')
class LogChanges(models.Model): #table to save the changes
    prevRemarks = models.CharField(max_length=500,default='')

forms.py

class troubleTicket(ModelForm):
    class Meta:
        model = tblTicket
        fields = '__all__'

class history(ModelForm):
    class Meta:
        model = LogChanges
        fields = '__all__'

views.py

def updateTicket(request, ticket_id):
    ticketDetails=tblTicket.objects.get(id=ticket_id)
    updateTicketForm = troubleTicket(request.POST or None,instance=ticketDetails)
    if updateTicketForm.is_valid():
        updateTicketForm.save()
        return HttpResponseRedirect('/ticket/')
    return render(request,'updateTicket.html', {'updateTicketForm':updateTicketForm,'ticketDetails':ticketDetails,'ticket_id':ticket_id})

I am using django 1.8.3


UPDATE:

I found a link related to my question. But it gives me an error NameError: name 'tblTicket' is not defined

def make_copy(sender, **kwargs):
    obj = kwargs['instance']
    try:
        orig_obj = tblTicket.objects.get(pk=obj.pk)
    except: #If it is a new object
        orig_obj = None

pre_save.connect(make_copy, sender=tblTicket) <- this is where the error leads me 

To my understanding, in this link , the Country there is the model. So I switched it to my model which is tblTicket . I don't understand why it isn't defined.

cIt sounds like you want to override the save method of your tblTicket model so that it creates a new LogChanges object. Like this..

class tblTicket(models.Model):
    ...

    def save(self):
        super(tblTicket, self).save()
        LogChanges.objects.create(prevRemarks=self.remarks)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM