Alexander
Alexander

Reputation: 727

Working with links in Django

I am working in a small blog application using Django. Sorry if the question is obvious, but I am a newbie. Actually it is my third since I started an online course. I have the following Queryset:

def all(request):
    allTiles = Post.objects.values('title')
    allPosts = Post.objects.all()[:3]
    context = {'Posts': allPosts,"Titles":allTiles}
    template = "home.html"
    return render(request, template, context)

and the follwing html code:

<ol class="list-unstyled">

            {% for singleTile in Titles %}
            <li><a href="#">{{singleTile.title}}</a></li>
            {% endfor %}
            </ol>

As you can see every title creates an link. Lets assume a person decides to read one of the posts. How can I use the title name and send a request back to the database to get the content of the post.

Upvotes: 0

Views: 47

Answers (2)

Raja Simon
Raja Simon

Reputation: 10305

You have to configure url first like

<a href="#">{% url 'app.views.post_id' singleTile.id %}</a></li>

In your urls

url(r'^post/(?P<post_id>\d+)/$', views.by_id, name='post_id'),

And in your views

def post_id(request, post_id):
   allTiles = Post.objects.get(id=post_id)
   return render(request, template, context)

Upvotes: 0

catavaran
catavaran

Reputation: 45555

It is better to use the id or slug field for such task.

But if you surely want to use the title as the GET parameter then apply the urlencode filter to the field's value:

<a href="{% url 'post_detail' %}?title={{ singleTile.title|urlencode }}">
    {{ singleTile.title }}
</a>

And the view will be something like this:

def post_detail(request):
    post = get_object_or_404(Post, title=request.GET.get('title'))
    return render(request, 'post_detail.html', {'post': post})

UPDATE: If you decide to go with the id/slug option then you can use the generic DetailView:

<a href="{% url 'post_detail' singleTile.id %}">
    {{ singleTile.title }}
</a

urls.py:

from django.views.generic.detail import DetailView
from app.models import Post

url(r'^post/(?P<pk>\d+)/$', DetailView.as_view(model=Post),
                            name='post_detail')

Upvotes: 1

Related Questions