使用 Javascript 实现 Live Django Search [英] Using Javascript to implement Live Django Search

查看:19
本文介绍了使用 Javascript 实现 Live Django Search的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Javascript 向我的电子商务项目添加搜索功能,我遵循了一个教程,该教程解释了在搜索栏中编写标题时只会出现具有相同字母的项目.在我的项目中,它适用于基本 HTML,但我试图让它更复杂一些,以包含包含价格等详细信息的完整卡片,而不仅仅是标题.

这是model.py

class Item(models.Model):标题=models.CharField(max_length=100)image = models.ImageField(blank=False,upload_to=upload_design_to)价格 = models.DecimalField(decimal_places=2, max_digits=100)折扣价格=models.DecimalField(decimal_places=2,max_digits=100,空白=真,空=真)时间戳 = 模型.DateTimeField(默认 = 时区.现在)

这是views.py

class ItemListView(ListView):型号 = 物品paginate_by = 12template_name = "store/product_list.html";排序 = ['-时间戳']def get_context_data(self, **kwargs):context = super().get_context_data(**kwargs)上下文[qs_json"] = json.dumps(list(Item.objects.values()),cls=DjangoJSONEncoder)返回上下文

这里是scripts.py

这里是template.html

<!--卡片--><div id="box"class='行卡组'>{% for item in object_list %}<div class="col-4 mb-3"><div class="card h-100"><a href="{{item.get_absolute_url}}"><embed src="{{ item.image.url }}";class="card-img-top";alt=..."/></a><div class="card-body"><h5 class="card-title">{{ item.title }}</h5><p class="card-text">{% if item.description %}{{ 商品描述 }}{% 万一 %}</p>

<div class="card-footer"><small class="text-muted">{{ item.timestamp }}</small>

{% 结束为 %}

<!--卡片-->

我的问题:如何将简单的 <b>${store['title']}</b><br> 替换为下面是带有整个卡片 div 及其所有相关信息的脚本?

如果需要更多信息或说明,请告诉我

 

<div class="card h-100"><a href="{{item.get_absolute_url}}"><embed src="{{ item.image.url }}";class="card-img-top";alt=..."/></a><div class="card-body"><h5 class="card-title">{{ item.title }}</h5><p class="card-text">{% if item.description %}{{ 商品描述 }}{% 万一 %}</p>

<div class="card-footer"><small class="text-muted">{{ item.timestamp }}</small>

解决方案

您的 template.html 页面已经使用 for-loop 生成了所有 html,因此您不必需要再次生成它们.相反,当用户输入时,您可以遍历所有 div 并检查 card-title div 是否具有 input 是否仅显示该 div 或其他隐藏它.

演示代码:

const input = document.getElementById('search_here')input.addEventListener('keyup', (e) => {var 输入 = e.target.value.toLowerCase();//做小写//遍历外部div并隐藏它document.querySelectorAll('.outers').forEach(function(el) {el.style.display = '无';});//循环通过外层->卡片标题document.querySelectorAll('.outers .card-title').forEach(function(el) {//相比if (el.textContent.toLowerCase().indexOf(inputs) > -1) {el.closest('.outers').style.display = "block";//如果匹配显示该div}})})

.outers {边框:1px纯蓝色;宽度:150px;高度:150px;边距底部:5px}

<input id="search_here" class="mb-2 form-control" placeholder="Type to search..."><div id="box" class='row card-group'><!--刚刚添加了一个额外的类--><div class="col-4 mb-3 外层"><div class="card h-100"><a href="{{item.get_absolute_url}}"><img src="{{ item.image.url }}" class="card-img-top" alt="..."/></a><div class="card-body"><h5 class="card-title">Somethings</h5><p class="card-text">有些东西……</p>

<div class="card-footer"><small class="text-muted">12:30:00</small>

<div class="col-4 mb-3 外层"><div class="card h-100"><a href="{{item.get_absolute_url}}"><img src="{{ item.image.url }}" class="card-img-top" alt="..."/></a><div class="card-body"><h5 class="card-title">Abc</h5><p class="card-text">有些东西……</p>

<div class="card-footer"><small class="text-muted">12:30:00</small>

<div class="col-4 mb-3 外层"><div class="card h-100"><a href="{{item.get_absolute_url}}"><img src="{{ item.image.url }}" class="card-img-top" alt="..."/></a><div class="card-body"><h5 class="card-title">def</h5><p class="card-text">有些东西……</p>

<div class="card-footer"><small class="text-muted">12:30:00</small>

I am adding a Search functionality to my E-commerce Project using Javascript, I have followed a tutorial that explains that when writing the title in the search bar only the items with the same letter appears. In my project, it was working fine for basic HTML but I am trying to make it a little more complex to include a complete card with some details such as price, not just the title.

Here is the model.py

class Item(models.Model):
    title = models.CharField(max_length=100)
    image = models.ImageField(blank=False, upload_to=upload_design_to)
    price = models.DecimalField(decimal_places=2, max_digits=100)
    discount_price = models.DecimalField(decimal_places=2, max_digits=100, blank=True, null=True)
    timestamp = models.DateTimeField(default=timezone.now)

Here is the views.py

class ItemListView(ListView):
    model = Item
    paginate_by = 12
    template_name = "store/product_list.html"
    ordering = ['-timestamp']

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["qs_json"] = json.dumps(list(Item.objects.values()),cls=DjangoJSONEncoder)
        return context

Here is the scripts.py

<script>
    const data = '{{qs_json}}'

    const rdata = JSON.parse(data.replace(/&quot;/g, '"'))
    console.log(rdata)

    const input = document.getElementById('search_here')
    console.log(input)

    let filteredArr = []

    input.addEventListener('keyup', (e)=>{
        box.innerHTML = ""
        filteredArr = rdata.filter(store=> store['title'].includes(e.target.value))
        console.log(filteredArr)
        if (filteredArr.length > 0){
            filteredArr.map(store=>{
                box.innerHTML += `<b>${store['title']}</b><br>`
            })
        } else {
            box.innerHTML = "<b>No results found...</b>"
        }
    })
</script>

Here is the template.html

<input id="search_here" class="mb-2 form-control" placeholder="Type to search...">

<!--Card-->
<div id="box" class='row card-group'>
{% for item in object_list %}
  <div class="col-4 mb-3">
    <div class="card h-100">
        <a href="{{item.get_absolute_url}}">
      <embed src="{{ item.image.url }}" class="card-img-top" alt="..."/>
        </a>
      <div class="card-body">
        <h5 class="card-title">{{ item.title }}</h5>
          <p class="card-text">
        {% if item.description %}
            {{ item.description }}
        {% endif %}
        </p>
      </div>
      <div class="card-footer">
        <small class="text-muted">{{ item.timestamp }}</small>
      </div>
    </div>
  </div>
{% endfor %}
</div>
<!--Card-->

My Question: How do I replace the simple <b>${store['title']}</b><br> with the below in the scripts with the whole card div with all its information related to it?

If any more information or clarifications required let me know

  <div class="col-4 mb-3">
    <div class="card h-100">
        <a href="{{item.get_absolute_url}}">
      <embed src="{{ item.image.url }}" class="card-img-top" alt="..."/>
        </a>
      <div class="card-body">
        <h5 class="card-title">{{ item.title }}</h5>
          <p class="card-text">
        {% if item.description %}
            {{ item.description }}
        {% endif %}
        </p>
      </div>
      <div class="card-footer">
        <small class="text-muted">{{ item.timestamp }}</small>
      </div>
    </div>
  </div>

解决方案

Your template.html page already have all htmls generated using for-loop so you don't need to generate them again .Instead , when user type you can loop through all div and check if card-title div has that input if it has simply show that div or else hide it.

Demo Code :

const input = document.getElementById('search_here')
input.addEventListener('keyup', (e) => {
  var inputs = e.target.value.toLowerCase(); //do lowercase
  //loop through outer div and hide it
  document.querySelectorAll('.outers').forEach(function(el) {
    el.style.display = 'none';
  });
  //loop through outer ->card-title
  document.querySelectorAll('.outers .card-title').forEach(function(el) {
    //compare 
    if (el.textContent.toLowerCase().indexOf(inputs) > -1) {
      el.closest('.outers').style.display = "block"; //if match show that div
    }
  })
})

.outers {
  border: 1px solid blue;
  width: 150px;
  height: 150px;
  margin-bottom: 5px
}

<input id="search_here" class="mb-2 form-control" placeholder="Type to search...">
<div id="box" class='row card-group'>
  <!--just added one extra class-->
  <div class="col-4 mb-3 outers">
    <div class="card h-100">
      <a href="{{item.get_absolute_url}}">
        <img src="{{ item.image.url }}" class="card-img-top" alt="..." />
      </a>
      <div class="card-body">
        <h5 class="card-title">Somethings</h5>
        <p class="card-text">
          some things ...
        </p>
      </div>
      <div class="card-footer">
        <small class="text-muted">12:30:00</small>
      </div>
    </div>
  </div>
  <div class="col-4 mb-3 outers">
    <div class="card h-100">
      <a href="{{item.get_absolute_url}}">
        <img src="{{ item.image.url }}" class="card-img-top" alt="..." />
      </a>
      <div class="card-body">
        <h5 class="card-title">Abc</h5>
        <p class="card-text">
          some things ...
        </p>
      </div>
      <div class="card-footer">
        <small class="text-muted">12:30:00</small>
      </div>
    </div>
  </div>
  <div class="col-4 mb-3 outers">
    <div class="card h-100">
      <a href="{{item.get_absolute_url}}">
        <img src="{{ item.image.url }}" class="card-img-top" alt="..." />
      </a>
      <div class="card-body">
        <h5 class="card-title">def</h5>
        <p class="card-text">
          some things ...
        </p>
      </div>
      <div class="card-footer">
        <small class="text-muted">12:30:00</small>
      </div>
    </div>
  </div>
</div>

这篇关于使用 Javascript 实现 Live Django Search的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆