Model instance not reflecting data passed from pre_save in custom field
<p>I have a custom field for generating slug and I am using it in my model.</p>

<p>The strange thing I can't figure out is why is the value I am generating in this custom field's method <code>pre_save</code> not set on the current instance. </p>

<p><strong>My question is not about generating slug different way but about this behavior.</strong></p>

<p>To simplify this example I defined this classes:</p>

<p>Model:</p>

<pre><code>class MyModel(models.Model):
    slug = MyCustomField(blank=True)

    def save(self, *args, **kwargs):
        super(MyModel, self).save(*args, **kwargs)
        print 'in save'
        print self.slug
</code></pre>

<p>Field:</p>

<pre><code>class MyCustomField(models.SlugField):
    def pre_save(self, model_instance, add):
        value = super(MyCustomField, self).pre_save(model_instance, add)
        if not value:
            value = 'random-generated-slug'
        return value
</code></pre>

<p>Post save signal:</p>

<pre><code>@receiver(post_save, sender=MyModel)
def test(sender, **kwargs):
    print 'in signal'
    print kwargs['instance'].slug
    print 'from database'
    print MyModel.objects.get(pk=kwargs['instance'].pk).slug
</code></pre>

<p>Code to run:</p>

<pre><code>instance = MyModel()
instance.save()
&gt;&gt; 'in signal'
&gt;&gt; ''
&gt;&gt; 'in database'
&gt;&gt; 'random-generated-slug'
&gt;&gt; 'in save'
&gt;&gt; ''
instance.slug
&gt;&gt; ''
</code></pre>

<p>Like you can see, the value is set in the database, but it's not on the current instance nor in post_save signal.</p>

<p>I have Django version 1.10. Should I set the value in a different way in <code>MyCustomField</code>? What is going on?</p>

<p>EDIT:
Maybe I should set this value in field's <code>save_form_data</code> or where is the best place to do this?</p>

<p>The instance's slug field was updated between the call to save and the write into the database. The current instance's slug value is <em>stale</em></p>

<p>To get the slug value which was written into the DB, the instance has to updated by <em>refetching</em> from the database:</p>

<pre><code>instance = MyModel.objects.get(pk=your_pk)
</code></pre>

python django