python - 每当我在 django 的搜索栏中输入内容时,如何使 require 对象可用?

标签 python html django

我创建了一个搜索栏,但每当我在其中写入内容时,链接都会显示 http://127.0.0.1:8000/?srh=something 并且我不明白为什么具体 带标题的图片未显示。它向我显示了所有带有标题的图片,但我只想要带有标题的图片,我在搜索栏中写为标题。这段代码中需要添加哪些内容?

index.html

{% load static %}
{% static 'images/fulls' as baseUrl %}
{% static 'images/thumbs' as hiUrl %}  

    <form class="new" method="GET" action="">
    <input type="text" placeholder='Search..' name="srh" value="{{request.GET.srh}}"> <br>
     <button type="submit" class="btn btn-danger"> Search </button>
    </form>

   <div>
    {% for dest1 in target1 %}
    {% if dest1 %}
     <div>
      <a href="{{baseUrl}}/{{dest1.img}}">
       <img src="{{hiUrl}}/{{dest1.img}}" alt="" />
       <h3>{{dest1.title}}</h3>
     </a>
   </div>
   {% endif %}
   {%endfor%}
  </div>

views.py

def index(request):
    query = request.GET.get('srh')
    if query:
        match = Destination.objects.filter(title__icontains=query)

        target1 = a, b= [Destination() for __ in range(2)]
        a.img = 'Article.jpg'
        b.img = 'Micro Tasks.jpeg'

        a.title = 'Article Writing'
        b.title = 'Micro Tasks'

        context = {
        'target1': target1,
       }
        return render(request, 'index.html', context)
    else:
       return render(request, 'index.html')

models.py

class Destination(models.Model):
    title = models.CharField(max_length=255)
    img = models.CharField(max_length=255)
    price = models.IntegerField()

最佳答案

我不明白你为什么使用 a 和 b,但我认为这可以解决问题

def index(request):
    query = request.GET.get('srh')

    if query:
        match = Destination.objects.get(desc=query)
        context = {
            'match': match,
        }

        return render(request, 'index.html', context)
    else:
        return render(request, 'index.html')
<div>
    { % if match %}
     <div>
      <a href="{{baseUrl}}/{{match.img}}">
       <img src="{{hiUrl}}/{{match.img}}" alt="" />
       <h3>{{match.title}}</h3>
     </a>
   </div>
   {% endif %}
  </div>

关于python - 每当我在 django 的搜索栏中输入内容时,如何使 require 对象可用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57024837/

相关文章:

python - 数据框条件列减去直到零

python - 如何向量化分类数据

python - Django REST Framework - 教程 - 困惑

python - 为什么 spritecillide 在 pygame 中工作不正常

javascript - HTML 如何使用 JavaScript 显示计时器?

java - 如何将 html 表单中的输入类型 "date"值转换为 java 变量和 SQL 日期格式?

css - 在使用 Chrome 打印分页前背景不适合的 div 框时,如何不显示框两次?

ruby-on-rails - Ruby on Rails 用于 Web 应用程序,Django 用于网页?

django - 在博客文章中添加下一个/上一个按钮

database - 如何在 Google App Engine/Django-nonrel 中存储一长串数字?