Reputation: 2615
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
Any help is much appreciated..Thanks in advace
Upvotes: 1
Views: 1262
Reputation: 8970
The error says that the id
field in the Post
model (which django creates itself) is an AutoField
(check this) which is basically a bigint
field in terms of sql
. Hence while querying on id
field it expects a mandatory int
value else will raise
an exception
.
In your case, the Post
model should have a slug
field, if it doesn't kind create one as below,
class Post(models.Model):
...
...
slug = models.SlugField(max_length=100)
...
...
And update your query as,
post = Post.objects.get(slug=slug)
Upvotes: 1
Reputation: 967
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>)
Upvotes: 3