如何在Django中使用Ajax过滤数据?

时间:2019-05-02 09:53:28

标签: ajax django

在这里我试图根据菜单类别过滤菜肴,并且我想在此页面中显示该选定类别的菜肴而不加载整个页面。我试图这样做,但这根本不起作用。仅在“所有”选项中。在“所有”选项中,所有活动食品都显示,这很好,但在其他选项中,则不显示任何内容。如何在不加载页面的情况下,在此页面中获取所选类别的菜肴。关于ajax和jquery的知识很少,所以我无法使用。任何人都可以帮助我编辑我的问题。这将是一个很大的帮助。

  

models.py

class MenuCategory(models.Model):
    title = models.CharField(max_length=250)
    slug = AutoSlugField(populate_from='title')
    date = models.DateTimeField(auto_now_add=True)
    active = models.BooleanField(default=True)


    def __str__(self):
        return self.title

    class Meta:
        verbose_name_plural = 'Menu Category'

class Food(models.Model):
    name = models.CharField(max_length=250)
    price = models.CharField(max_length=100)
    detail = models.TextField(blank=True)
    category = models.ForeignKey(MenuCategory,on_delete=models.DO_NOTHING)
    image = models.ImageField(upload_to='Foods',blank=True)
    featured = models.BooleanField(default=False)
    active = models.BooleanField(default=True)
    date = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name_plural = 'Foods'
  

views.py

def homepage(request):
    menu_categories = MenuCategory.objects.filter(active=True)
    foods = Food.objects.filter(active=True)
     return render(request,'cafe/base.html',{ 'menu_categories':menu_categories,
                                            'foods':foods,}
def category_dishes(request):
    category = MenuCategory.objects.get(id=request.GET.get('category_id'))
    return render(request, 'cafe/category_dishes.html', {'category':category})
  

urls.py

path('',views.homepage),
  path('ajax/load-category-dishes/', views.category_dishes),
  

category_dishes.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
 <div class="iso-item" id="dishes2" data-aos="zoom-in-up" data-aos-duration="1000">
{% for food in category.food_set.all %}
         <div class="item dessert dinner"> <!-- Iso-Item .// --> <!-- Alternate .// -->
            <div class="menu-card-main">
                <div class="menu-card-image recommend">
                    <a href="/media/{{food.image}}" data-lightbox="menu4" data-title="Smoked Paprika Hum"><img src="/media/{{food.image}}" alt="Dish4"></a>
                </div>
                <div class="manu-card-content main-box">
                    <p class="dish-price text-center u-margin-bottom-mini">{{food.price}}</p>
                    <h4 class="dish-name text-center u-margin-bottom-small">{{food.name}}</h4>
                    <p class="dish-detail text-center">{{food.detail}}</p>
                </div>
            </div>
        </div>
     {% endfor %}   <!-- Iso-Item .// -->



    </div>
</body>
</html>
  

base.html

<section class="menu-main common-padding" id="menu">
    <div class="container"> <!-- Container .// -->
{% for section in menu_sections %}
        {% if forloop.last %}
        <div class="section-heading-wrap">
            <p class="sub-heading" data-aos="fade-left" data-aos-duration="1000">{{section.section_title}}</p>
            <h3 class="main-heading u-margin-bottom-small" data-aos="fade-right" data-aos-duration="1000">{{section.title_info}}</h3>
            <p class="section-subtitle text-center normal-content" data-aos="fade-up" data-aos-duration="1000">{{section.section_description}}</p>
        </div>
        {% endif %}
   {% endfor %}

    </div> <!-- Container .// -->

    <div class="iso-menu">
        <ul> <li class="active" data-filter="*">All</li>
            {% for category in menu_categories %}
            <li data-filter="{{category.id}}"  id="#dishes1" data-dishes-url="/ajax/load-category-dishes/">{{category.title}}</li>
            {% endfor %}
        </ul>
    </div>
     <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
  <script>
    $("#dishes1).change(function () {
      var url = $("#dishes1").attr("data-dishes-url");
      var category_id = $(this).val();
      $.ajax({
        url: url,
        data: {
          'category_id': category_id
        },
        success: function (data) {
          $("#dishes2").html(data);
        }
      });

    });
  </script>
    <div class="iso-item" id="#dishes2" data-aos="zoom-in-up" data-aos-duration="1000">
{% for food in foods %}
        {% if food.featured %}
         <div class="item dessert dinner"> <!-- Iso-Item .// --> <!-- Alternate .// -->
            <div class="menu-card-main">
                <div class="menu-card-image recommend">
                    <a href="/media/{{food.image}}" data-lightbox="menu4" data-title="Smoked Paprika Hum"><img src="/media/{{food.image}}" alt="Dish4"></a>
                </div>
                <div class="manu-card-content main-box">
                    <p class="dish-price text-center u-margin-bottom-mini">{{food.price}}</p>
                    <h4 class="dish-name text-center u-margin-bottom-small">{{food.name}}</h4>
                    <p class="dish-detail text-center">{{food.detail}}</p>
                </div>
            </div>
        </div>
        {% else %}
        <div class="item dinner lunch"> <!-- Iso-Item .// -->
            <div class="menu-card-main">
                <div class="manu-card-content main-box">
                    <p class="dish-price text-center u-margin-bottom-mini">{{food.price}}</p>
                    <h4 class="dish-name text-center u-margin-bottom-small">{{food.name}}</h4>
                    <p class="dish-detail text-center">{{food.detail}}</p>
                </div>
                <div class="menu-card-image">
                    <a href="/media/{{food.image}}" data-lightbox="menu1" data-title="Grilled American Fillet"><img src="/media/{{food.image}}" alt="Dish1"></a>
                </div>
            </div>
        </div>
        {% endif %}
     {% endfor %}   <!-- Iso-Item .// -->



    </div>
</section>

1 个答案:

答案 0 :(得分:1)

检查调试控制台类别ID是否显示

  $("#dishes1).change(function () {
      var url =  'ajax/load-category-dishes/'  //$("#dishes1").attr("data-dishes-url");
      var category_id = $(this).val();
      console.log(category_id)
      $.ajax({
        url: url,
        type: "GET",
        data: {
          'category_id': category_id
        },
        success: function (data) {
          $("#dishes2").html(data);
        }
      });

ajax通话非常完美,现在您需要编写视图

更新

import json
from django.http import JsonResponse
from django.core.serializers.json import DjangoJSONEncoder
from django.core import serializers


def category_dishes(request):
    if request.is_ajax():
        category = MenuCategory.objects.get(id=request.GET.get('category_id'))
        data = serializers.serialize('json', [category, ])
        struct = json.loads(data)
        data = json.dumps(struct)

    else:
        data = "Not ajax"
    return HttpResponse(data)

HttpResponse将数据发送到您的Ajax成功函数