Home > Back-end >  How to request url of that model detail views in search result?
How to request url of that model detail views in search result?

Time:09-16

I am searching in three model and all model has different detail views and but i am unable to figure out how to tell django to locate the view acc to their model this is my view for seaching in models

def search_item(request): results = [] search_item = request.GET.get("search")

if search_item:
    q = Q(title__icontains=search_item) | Q(written_by__icontains=search_item)
    for model in (crypto, News, Movie):
        results.extend(model.objects.filter(q))

return render(request, "result.html", {"results": results})

and for that template

{% for result in results %}
  <a class="blog-card" href="">
    <div class="card col-4" style="width: 18rem;">
      <img src="{{ result.title_image.url }}" class="card-img-top" width="100%" height="200px">
      <div class="card-body">
        <h5 class="card-title text-center" style="color:black">{{ result.title|truncatewords:7 }}</h5>
        <p class="card-text text-center" style="color:black">{{ result.info|truncatewords:10 }}</p>
        <p class="number text-center" style="color: black;"> Wriiten By:<strong> {{ result.written_by }}</strong></p>
        <p class="last text-center" style="color: black;"> Last update:<strong> {{ result.joined_date }}</strong></p>
      </div>
    </div>
  </a>
{% endfor %}

and all the model has different detail views, so how to do that urls.py

  path('crypto/<slug:title>/',views.ttt_read,name="ttt_read"),
    path('news/<slug:title>/',views.news_read,name="news_read"),
    path('movie/<slug:title>/',views.movie_read,name="movie_read"),
    path('penmen/search/',views.search_item,name='search')

any help and suggestion will be appreciated

CodePudding user response:

For each model define a get_absolute_url() method.

Example:

    from django.urls import reverse

    class News(models.Model):
        ...
        def get_absolute_url(self):
            return reverse('news_read', args=[slug(self.title)])

Then in your template you can just do:

    ...
    <a class="blog-card" href="{{result.get_absolute_url}}">
    ...
  • Related