[Answered ]-How to pass url to a model field lookup in django

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

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

Leave a comment