How to allow user to edit post with Django?

1.7k Views Asked by At

In my blog I decided to allow users to edit posts (I am using Django), but I am not sure what is the right implementation for my models to do that. Is a good idea to use multi-table inheritance as my code below? I also want to keep track of all the posts, originals as the every new edited as well.

class Post(models.Model):
    title = models.CharField(max_length=500)
    text = models.TextField()
    creation_date = models.DateTimeField(auto_now_add=True)
    user = models.ForeignKey(User)

    def __unicode__(self):
        return "%s %s by %s" % (self.title, self.creation_date, self.user)

class Edit(Post):
    edited_date = models.DateTimeField(auto_now_add=True)
    editor = models.OneToOneField(User)

    def __unicode__(self):
        return "%s edited by %s" % (self.convention, self.login)
1

There are 1 best solutions below

2
Bibhas Debnath On BEST ANSWER

What you need is version control. There are apps that can implement it. But if you want to do it yourself, then your Edit model must have a reference to the Post models. And must point to a specific post corresponding to the author of that edit. That necessarily means you have to create a Post instance every time a post is saved and you must point to that new instance from the Edit instance.

Something like this, but may need more work -

class Post(models.Model):
    title = models.CharField(max_length=500)
    text = models.TextField()
    creation_date = models.DateTimeField(auto_now_add=True)
    edited_date = models.DateTimeField(auto_now_add=True)
    author = models.ForeignKey(User)

    def __unicode__(self):
        return "%s at %s by %s" % (self.title, self.creation_date, self.author.first_name)

class Edit(models.Model):
    creation_date = models.DateTimeField(auto_now_add=True)
    editor = models.ForeignKey(User)
    post = models.ForeignKey(Post)

    def __unicode__(self):
        return "%s edited by %s" % (self.post.title, self.editor.first_name)