Search code examples
djangomodels

Django URL Slugs


I have a comment and a post model.

I want the URL to come out as /post//comment//

But I am unsure how to set this up.

My Post model has this:

@python_2_unicode_compatible
class Post(models.Model):
    ...
    slug = models.SlugField(unique=True)

    @models.permalink
    def get_absolute_url(self):
        return 'appname:post', (self.slug,)

can my comment model have:

@python_2_unicode_compatible
class Comment(models.Model):
    ...
    slug = models.SlugField(unique=True)

    @models.permalink
    def get_absolute_url(self):
        return 'appname:post:comment', (self.slug,)

or how do I hook up get_absolute_url so that the url comes out the way I mentioned? or is there a better way?


Solution

  • @python_2_unicode_compatible
    class Comment(models.Model):
        title = models.CharField(max_length=100)
        body = models.CharField(max_length=1000)
        creation_date = models.DateTimeField(auto_now_add=True)
        last_updated = models.DateTimeField()
        author = models.ForeignKey(Person, related_name='authors')
        project = models.ForeignKey(Project, related_name='comments', null=True, blank=True)
        task = models.ForeignKey(Task, related_name='comments', null=True, blank=True)
        slug = models.SlugField(unique=True)
    
        def __str__(self):
            return self.title    
    
        @models.permalink
        def get_absolute_url(self):
            if self.project:
                return ('comment', (), {
                    'project': self.task.id,
                    'slug': self.slug,
                    'id': self.id,
                })            
            elif self.task:
                return ('comment', (), {
                    'project': self.task.project.id,
                    'task': self.task.id,
                    'slug': self.slug,
                    'id': self.id,
                })
    

    and then hook up the urls.py to use all the necessary id's for the url named 'comment'