Home > Mobile >  How to make a search filter on the django website
How to make a search filter on the django website

Time:08-12

I have a database with the name of the attached files 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%;"  data-aos="fade-up">
                <form action="" method="post" style="width:90%">
                     {% csrf_token %}
<!--                       {{form|crispy}}-->
                     <p><label  for="{{ form.number_course.id_for_label }}">Курс: </label> {{ form.number_course }}</p>
                          <div >{{ form.number_course.errors }}</div>
                     <p><label  for="{{ form.number_semestr.id_for_label }}">Семестр: </label> {{ form.number_semestr }}</p>
                          <div >{{ form.number_semestr.errors }}</div>
                    <p><label  for="{{ form.subjectt.id_for_label }}">Дисциплина </label> {{ form.subjectt }}</p>
                          <div >{{ form.subjectt.errors }}</div>
                     <p><select name = "type_materials" required  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  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 >{{ form.institute.errors }}</div>
                    <button type="submit" >Найти</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:

   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.

CodePudding user response:

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.

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

And your view is filtering using the data passed as GET

form = FileFilterForm(request.GET)

You should create a for with a method="get" to make it work.

To make this easier you can use django-filter

  • Related