Home > Net >  Why can't I filter the data by one known in django&
Why can't I filter the data by one known in django&

Time:08-13

I have a painted filter in view.py which works wonderfully. When I use a common abbreviation in html code, like {{form.as_p}} or {{form|crispy}}, then I can find the data I need, according to one known one. In my case, this is by course, by semester, by type of subject, by institute, and so on, and when I start writing my html code, in order for the search to give the correct answer, all fields must be filled in, although in forms and models I determined that all fields are not required, it turns out that an error in the html code, but I do not know where(

veiws.py:

def buy_files(request):
bdfiles = FeedFile.objects.all()
# bdfiles = UploadFile.objects.all()
form = FileFilterForm(request.GET)
if form.is_valid():
    if form.cleaned_data["number_course"]:
        bdfiles = bdfiles.filter(feed__number_course = form.cleaned_data["number_course"])
    if form.cleaned_data["number_semestr"]:
        bdfiles = bdfiles.filter(feed__number_semestr = form.cleaned_data["number_semestr"])
    if form.cleaned_data["subjectt"]:
         bdfiles = bdfiles.filter(feed__subjectt = form.cleaned_data["subjectt"])
    if form.cleaned_data["type_materials"]:
         bdfiles = bdfiles.filter(feed__type_materials = form.cleaned_data["type_materials"])
    if form.cleaned_data["institute"]:
        bdfiles = bdfiles.filter(feed__institute = form.cleaned_data["institute"])

return render(request, 'chat/files/buyfile.html', {'bdfiles': bdfiles, 'form':form})

html code:

            <div style="float: right; margin-bottom: 10%; margin-top: 10%;"  data-aos="fade-up">
                <form action="" method="get" style="width:90%">
                     {% csrf_token %}
<!--                       {{form|crispy}}-->
                     <p><label >Курс: </label> {{ form.number_course }}</p>
                          <div >{{ form.number_course.errors }}</div>
                     <p><label >Семестр: </label> {{ form.number_semestr }}</p>
                          <div >{{ form.number_semestr.errors }}</div>
                    <p><label >Дисциплина </label> {{ form.subjectt }}</p>
                          <div >{{ form.subjectt.errors }}</div>
                     <p><select name = "type_materials"  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"  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>

forms.py

class FileFilterForm(forms.Form):

number_course = forms.IntegerField(label='Курс',required=False, widget=forms.NumberInput(attrs={'class': 'form-control'}))
number_semestr = forms.IntegerField(label='Семестр',required=False, widget=forms.NumberInput(attrs={'class': 'form-control'}))
subjectt = forms.CharField(label='Дисциплина',required=False,widget=forms.TextInput(attrs={'class': 'form-control'}))
type_materials = forms.CharField(label='Тип материала',required=False,widget=forms.TextInput(attrs={'class': 'form-control'}))
institute = forms.CharField(label='Институт',required=False,widget=forms.TextInput(attrs={'class': 'form-control'}))

CodePudding user response:

When you generate a form by something like {{form.as_p}}, all the fields are generated and submitted, even if some of the values associated with them are empty because no choice is made by the user.

When you write out only a few fields, the missing fields aren't submitted at all.

That means, in your views.py, when you refer to them by

form.cleaned_data["number_course"]

you might get an invalid key error, as no data by that name was submitted.

To fix, you can use

form.cleaned_data.get('number_course')

...which should return None if there is no such key, rather than erroring out

  • Related