1

Having some trouble finding how to pass a var captured in a url to my view.

say I have a model like this...

title = models.CharField()

and a title of...

title = 'this is a post'

then how would django capture something in the URL like this...

url/this_is_a_post/

and lookup the model field like this...

x = Post.objects.get(title='this is a post')

I have another URL that is capturing a name with a space in it, and when I use a URL with "_"'s in it, it looks it up correctly, but in this case, it is telling me there is no matching query. I have tried to look in the docs, but I couldn't find anything although I know it has to be there, somewhere.

Joff
  • 11,247
  • 16
  • 60
  • 103
  • 1
    Go through https://docs.djangoproject.com/en/1.9/ref/models/fields/#slugfield, you have to use slugfield for this type of situations. – Geo Jacob Dec 17 '15 at 06:58
  • @GeoJacob that is what I need, but the docs don't seem to have much info about how to use it? How can I discern that from docs like this? I have always wondered about this – Joff Dec 17 '15 at 07:02
  • It's already answered here clearly, please check it http://stackoverflow.com/questions/427102/what-is-a-slug-in-django – Geo Jacob Dec 17 '15 at 07:07
  • Actually, IMO it is not answered clearly there because there is no explanation to what it does, people say use it as the title field, but then what....? Does it auto convert a title into a slug when queried? Do I need a title character field for my actual title and then a separate slug field where I manually type in the slug I want to use? and then query that? It is actually quite vague – Joff Dec 18 '15 at 02:57
  • Please check the answer. – Geo Jacob Dec 18 '15 at 06:00

2 Answers2

2

Use two fileds in your models, say;

class Post(models.Model):
    title = models.CharField(max_length=100)
    slug = models.SlugField(max_length=100)

and while saving yor Post, you shoud save slug also;

In views;

from django.template.defaultfilters import slugify

post = Post.objects.create(title=title, slug=slugify(title))

this slug will be unique for each post.

In urls.py

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

In views.py

def post_detail(request, slug):
    x = Post.objects.get(slug=slug)
Geo Jacob
  • 5,909
  • 1
  • 36
  • 43
0

in models.py:

title = models.SlugField(unique=True)

in urls.py:

 urlpatterns = [
    ...
    url(r'^(?P<title>\d+)/$', views.article_view, name = 'article_detail'),
    ...
    ]

in views.py:

def article_view(request, title):
    ...
    article = get_object_or_404(Article, title=title)
    ...

in template.html:

<a href="{% url 'article_detail' title=article.title %}">
Balas
  • 135
  • 8