Code

Opened 4 years ago

Closed 4 years ago

#13220 closed (invalid)

Documentation on pre- and post-save/delete hooks misses key arguments

Reported by: nikoftime Owned by: nobody
Component: Documentation Version: 1.2-beta
Severity: Keywords: pre save, post save, hook, delete hook, save hook
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: UI/UX:

Description

The documentation at http://www.djangoproject.com/documentation/models/save_delete_hooks/

Has the following code example:

from django.db import models

class Person(models.Model):
    first_name = models.CharField(max_length=20)
    last_name = models.CharField(max_length=20)

    def __unicode__(self):
        return u"%s %s" % (self.first_name, self.last_name)

    def save(self):
        print "Before save"
        super(Person, self).save() # Call the "real" save() method
        print "After save"

    def delete(self):
        print "Before deletion"
        super(Person, self).delete() # Call the "real" delete() method
        print "After deletion"

However, using method definitions like these to override models.Model.save() and .delete() causes some problems with the optional arguments to both functions.
A better way to do this might be to have the method signatures use *args, and kwargs, so that arguments to these overridden methods are properly passed to the parent method implementations:

from django.db import models

class Person(models.Model):
    first_name = models.CharField(max_length=20)
    last_name = models.CharField(max_length=20)

    def __unicode__(self):
        return u"%s %s" % (self.first_name, self.last_name)

    def save(self, *args, **kwargs):
        print "Before save"
        super(Person, self).save(*args, **kwargs) # Call the "real" save() method
        print "After save"

    def delete(self, *args, **kwargs):
        print "Before deletion"
        super(Person, self).delete(*args, **kwargs) # Call the "real" delete() method
        print "After deletion"

This also helps future-proof overridden method implementations to changes in the Django core.

Attachments (0)

Change History (1)

comment:1 Changed 4 years ago by russellm

  • milestone 1.2 deleted
  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset
  • Resolution set to invalid
  • Status changed from new to closed

What you've found isn't current Django documentation; it's documentation from the 0.96 era. It #13201 covers the process of deprecating these documentation pages.

Add Comment

Modify Ticket

Change Properties
<Author field>
Action
as closed
as The resolution will be set. Next status will be 'closed'
The resolution will be deleted. Next status will be 'new'
Author


E-mail address and user name can be saved in the Preferences.

 
Note: See TracTickets for help on using tickets.