Note that there are some explanatory texts on larger screens.

plurals
  1. POManyToMany field not saved when using Django admin
    primarykey
    data
    text
    <p>I'm experiencing a weird problem which I hope someone in here may be able to shed some light on.</p> <p>I'm overriding the save() method of a model to add some values to a ManyToMany-field after running super(). My problem is that when I'm saving in Django admin the values seems to get added to the relationship but is then empty again.</p> <p>If however I do it from <code>manage.py shell</code> it works without problem.</p> <p>I've put two print statements in there and they produce the exact same output regardless of if I'm running it via Django admin or via shell.</p> <pre><code>class Store(models.Model): holidays = models.ManyToManyField(StoreHoliday, blank=True) copy_holidays_from = models.ForeignKey('Store', blank=True, null=True) def save(self): print '==== BEFORE SAVE:', self.holidays.all() super(Store, self).save() self.copy_holidays() print '==== AFTER SAVE:', self.holidays.all() def copy_holidays(self): if self.pk and self.copy_holidays_from: self.holidays.clear() for h in self.copy_holidays_from.holidays.all(): self.holidays.add( h ) </code></pre> <p>This is the output of the <code>print</code> statements:</p> <pre><code>==== BEFORE SAVE: [] ==== AFTER SAVE: [&lt;StoreHoliday: 10 Mar 2010, Chuck Norris birthday (Closed)&gt;] </code></pre> <p>Does anyone have any suggestions on what might be causing this? </p> <p><strong>Edit:</strong> All manual changes to the m2m relationship in save() seems to be discarded by Django when saving through the admin interface. Is this related to how it processes the form?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload