Search code examples
djangodjango-urlsslug

Django How to represent slug as ID for function based view


Im learning django and came across slug and Im struck while sending arguments to function based view

My urls.py

url(r'^(?P<slug>[\w-]+)/$', views.detail, name='detail'),

Views.py

def detail(request, slug):
    post = Post.objects.get(id=slug)
    comments=post.comment_set.all()
    forms=CommentForm
    if request.method == 'POST':
        form=CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.title = post
            print comment
            comment.save()
        else:
          print form.errors
    else:
        form = PostForm()

model.py

class Post(models.Model):
    title=models.CharField(max_length=200)
    description=models.TextField(max_length=10000)
    pub_date=models.DateTimeField(auto_now_add=True)
    slug = models.SlugField(max_length=40, unique=True)

    def __unicode__(self):
        return self.title

    def description_as_list(self):
        return self.description.split('\n')

    def get_absolute_url(self):
        return reverse('detail',kwargs={'slug':self.slug })

In the second line of views of views.py post = Post.objects.get(id=slug),I feel this is wrong representation, What could be correct way of doing it?

I get following error for the above code enter image description here

Any help is much appreciated..Thanks in advace


Solution

  • Assuming your post model has a slug field, you'll want to do:

    post = Post.objects.get(slug=slug)
    

    which can be translated as:

    post = Post.objects.get(<name_of_field>=<argument_in_url>)