Question

I am using Django, and I have recently created a blog as my first Django/python project. I decided to use the default admin area for my blog management system, for simplicity. I would like to automatically post a twitter update when I initially create a blog post, but not when I edit it. I know how to send the tweet, but how would I run some code on the initial save of the post, and not after edits?

I'm using Django 1.5.4 and the model for blog posts is simply called "Post".

Was it helpful?

Solution

you can do this in at least two ways: You could override the model's save method like this:

class Post(models.Model):
    ...
    def save(self, *args, **kwargs):
       if not self.pk:
         #tweet about the post
       super(Post, self).save(*args, **kwargs)

..but if you want to associate this behavior only with django admin (e.g. you want to tweet about a post only when it is created through the admin app and not when explicit calls to Post.objects.create() are made), then you can use the save_model() method of the ModelAdmin class:

class PostAdmin(admin.ModelAdmin):
   ....
   def save_model(self, request, obj, form, change):
      if not obj.pk:
         #tweet about the post
      obj.save()

You can also take a look at https://docs.djangoproject.com/en/dev/ref/contrib/admin/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top