【问题标题】:How to request url of that model detail views in search result?如何在搜索结果中请求该模型详细视图的 url?
【发布时间】:2021-11-10 17:34:20
【问题描述】:

我在三个模型中搜索,所有模型都有不同的细节视图,但我无法弄清楚如何告诉 django 找到符合他们模型的视图 这是我对模型搜索的看法

def search_item(请求): 结果 = [] search_item = request.GET.get("搜索")

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})

对于那个模板

{% 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 %}

所有模型都有不同的细节视图,那么如何做到这一点 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')

任何帮助和建议将不胜感激

【问题讨论】:

    标签: django django-models django-views django-templates django-urls


    【解决方案1】:

    为每个模型定义一个get_absolute_url() 方法。

    例子:

        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}}">
        ...
    

    【讨论】:

    • 我已经用过,但看到你的我再次尝试它,它仍然可以工作,非常感谢你
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-27
    • 1970-01-01
    • 2018-07-14
    • 1970-01-01
    • 2012-12-06
    相关资源
    最近更新 更多