简体   繁体   English

如何在 django 网站上制作搜索过滤器

[英]How to make a search filter on the django website

I have a database with the name of the attached files models.py我有一个带有附加文件models.py 名称的数据库

   class UploadFile(models.Model):
        user = models.ForeignKey(User,on_delete = models.CASCADE,related_name='file_created' ,verbose_name='Автор')
        title = models.CharField(max_length=200, verbose_name='Заголовок')
        # uploadedfile = models.FileField(upload_to='files/',null=True, verbose_name='Файл')
        description = models.TextField(blank=True, verbose_name='Описание')
        createdtime = models.DateField(auto_now_add=True, db_index=True, verbose_name='Дата создания')
        price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, verbose_name='Цена')
        number_course = models.IntegerField(null=True, blank=True, verbose_name='Курс')
        number_semestr = models.IntegerField(null=True, blank=True, verbose_name='Семестр')
        subjectt = models.CharField(max_length=200, null=True,verbose_name='Предмет')
        type_materials = models.CharField(max_length=200,null=True, verbose_name='Тип работы')
        institute = models.CharField(max_length=200, null=True, verbose_name='Институт')

    def __str__(self):
        return self.title

    class Meta:
        verbose_name = 'Загрузка файла'
        verbose_name_plural = 'Загрузка файлов'

I need to make a filter on the table that is obtained when uploading a file: Page with table:我需要对上传文件时获得的表格进行过滤:带表格的页面:

     <div style="float: right; margin-bottom: 10%; margin-top: 10%;" class="form-group row" data-aos="fade-up">
                <form action="" method="post" style="width:90%">
                     {% csrf_token %}
<!--                       {{form|crispy}}-->
                     <p><label class="form-label" for="{{ form.number_course.id_for_label }}">Курс: </label> {{ form.number_course }}</p>
                          <div class="form-error">{{ form.number_course.errors }}</div>
                     <p><label class="form-label" for="{{ form.number_semestr.id_for_label }}">Семестр: </label> {{ form.number_semestr }}</p>
                          <div class="form-error">{{ form.number_semestr.errors }}</div>
                    <p><label class="form-label" for="{{ form.subjectt.id_for_label }}">Дисциплина </label> {{ form.subjectt }}</p>
                          <div class="form-error">{{ form.subjectt.errors }}</div>
                     <p><select name = "type_materials" required class="form-select" aria-label="Тип материала">
                          <option selected>Тип материала</option>
                          <option value="Практические работы">Практические работы</option>
                          <option value="Лабораторные работы">Лабораторные работы</option>
                          <option value="Курсовые">Курсовые</option>
                             <option value="Дипломная работа">Дипломная работа</option>
                         <option value="Лекции">Лекции</option>
                          <option value="Диск с работами">Диск с работами</option>
                         <option value="Другое">Другое</option>
                        </select></p>
                     <p><select name = "institute" required class="form-select" aria-label="Институт">
                          <option selected>Институт</option>
                          <option value="ИВТИ">ИВТИ</option>
                          <option value="ГПИ">ГПИ</option>
                          <option value="ИЭЭ">ИЭЭ</option>
                             <option value="ИГВИЭ">ИГВИЭ</option>
                          <option value="ИнЭИ">ИнЭИ</option>
                          <option value="ИРЭ">ИРЭ</option>
                         <option value="ИЭТЭ">ИЭТЭ</option>
                          <option value="ИТАЭ">ИТАЭ</option>
                          <option value="ИЭВТ">ИЭВТ</option>
                             <option value="ЭнМИ">ЭнМИ</option>
                         <option value="Другой">Другой</option>
                        </select></p>
                          <div class="form-error">{{ form.institute.errors }}</div>
                    <button type="submit" class="btn btn-primary">Найти</button>
                </form>
                    <div style="width:90%">
                        <br>
                    <table>
                        <tr>
                            <th>Заголовок</th>
                            <th>Описание</th>
                            <th>Институт</th>
                            <th>Курс</th>
                            <th>Семестр</th>
                            <th>Дисциплина</th>
                            <th>Цена</th>
                            <th>Тип материала</th>
                            <th>Файл</th>
                        </tr>
                        {% for bd in bdfiles %}
                        <tr>
                            <th>{{ bd.feed.title}}</th>
                            <th>{{ bd.feed.description }}</th>
                            <th>{{ bd.feed.institute }}</th>
                            <th>{{ bd.feed.number_course }}</th>
                            <th>{{ bd.feed.number_semestr }}</th>
                            <th>{{ bd.feed.subjectt }}</th>
                            <th>{{ bd.feed.price }}</th>
                            <th>{{ bd.feed.type_materials }}</th>
                            <th><a href="{{bd.file.url}}" download="{{bd.file.url}}">Купить</a></th>
                        </tr>
                        {% endfor %}
                    </table>
            </div>
</div>

And my searching code in views.py:还有我在views.py中的搜索代码:

   def buy_files(request):
        bdfiles = FeedFile.objects.all()
        upfiles = UploadFile.objects.all()
        form = FileFilterForm(request.GET)
        if form.is_valid():
            if form.cleaned_data["number_course"]:
                bdfiles = bdfiles.filter(number_course__exact = form.cleaned_data["number_course"])
            if form.cleaned_data["number_semestr"]:
                bdfiles = bdfiles.filter(number_semestr__exact = form.cleaned_data["number_semestr"])
            if form.cleaned_data["subjectt"]:
                 bdfiles = bdfiles.filter(course__in = form.cleaned_data["subjectt"])
            if form.cleaned_data["type_materials"]:
                 bdfiles = bdfiles.filter(course__in = form.cleaned_data["type_materials"])
        return render(request, 'chat/files/buyfile.html', {'bdfiles': bdfiles, 'form':form}) 

But when I try to filter the data, nothing happens.但是当我尝试过滤数据时,什么也没有发生。 I do not know how to make a search, for example, only by one item, for example, by course or by semester, and so on.我不知道如何进行搜索,例如仅按一项,例如按课程或按学期等。

If you are using this for to do de filtering using the submit button then the issue is that the form is sending a POST request.如果您使用它来使用提交按钮进行反过滤,那么问题是表单正在发送 POST 请求。

<form action="" method="post" style="width:90%">

And your view is filtering using the data passed as GET您的视图正在使用作为 GET 传递的数据进行过滤

form = FileFilterForm(request.GET)

You should create a for with a method="get" to make it work.您应该使用method="get"创建一个 for 以使其工作。

To make this easier you can use django-filter为了使这更容易,您可以使用django-filter

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM