过滤器-如何实施

时间:2019-05-22 08:34:45

标签: django django-models django-forms django-templates django-views

我需要在Django软件中实现多项选择过滤器。 我有我的模型(数据库):

models.py

class Autor(models.Model):
    naziv = models.CharField(max_length=30, null=False, blank=True)
    email = models.EmailField(max_length=75, null=True, blank=True)

    def __str__(self):
        return str(self.naziv)      

class Clanak(models.Model):
    naslov = models.CharField(null=False, blank=True, max_length=120)
    datumObjave = models.DateField(null=False, blank=False)
    autor = models.ForeignKey(Autor, on_delete=models.CASCADE, null=True)   

    def __str__(self):
        return str(self.naslov) + ', ' + str(self.datumObjave) + ', ' + str(self.autor)

我的urls.py:

urlpatterns = [
    path('filtar/',views.filtar, name='filtar'),
]

Views.py:

def filtar(request):
    form = ChoiceForm(request.GET or None)
    data = Clanak.objects.all()    
    if form.is_valid():
        if 'Choice 1' in form.cleaned_data['filter']:
            data = data.filter(naslov='name')
        if 'Choice 2' in form.cleaned_data['year']:
            data = data.filter(datumObjave__year='year')
    return render(request, 'filtar.html', {'data': data, 'form': form})

Filtar.html:

<!DOCTYPE html>
<html>
<head>
{% extends 'base.html' %}
{% block main_content %}
    <title></title>
</head>
<body>
<table border="1">

        <tr>
        <th>Naslov</th>
        <th>Datum</th>
        <th>Autor</th>
        </tr>
        {% for x in data %}
    <tr>
        <td>{{x.naslov}}</td>
        <td>{{x.datumObjave}}</td>
        <td>{{x.autor}}</td>
    </tr>   
    {% endfor %}
</table>
</body> 
</html>
{% endblock %}

footer.html

<br>
    <div>Filter: </div>
    <form>
      {% csrf_token %}
      <fieldset>
        <legend>Filtar - Thing that is being chosen</legend>

        {{ form.as_p }}

        <input type="submit" value="Submit">
      </fieldset>
    </form>
    <br>
    <div>Copyright by </div>

Forms.py

class ChoiceForm(forms.Form):
    filter = forms.MultipleChoiceField(choices=(('Choice 1', 'Choice 1'), ('Choice 2', 'Choice 2')), widget=forms.CheckboxSelectMultiple)
    name = forms.CharField(label='name')
    year = forms.CharField(label='year')

屏幕截图:

Image

现在我的问题是:

我的问题是,无论我在文本字段中编写什么内容,它都不会执行任何操作,只是使用所有相同的数据刷新页面。 动态创建的文本框的名称应为“ nameinput”和“ yearinput”

1 个答案:

答案 0 :(得分:2)

您的表单将向同一页面发送GET请求。因此,在视图开始处理时,它会同时获取两个选择值(如果存在),获取所有Clanak对象并根据选择的选项进行过滤。
这样,如果未选择过滤器,则将获取所有对象。如果同时选择两个过滤器,则将同时过滤名称和年份。

def filtar(request):
    choice1 = request.GET.get('Autor', None)
    choice2 = request.GET.get('Datum', None)
    data = Clanak.objects.all()
    if choice1:
        data = data.filter(naslov='NAME')
    if choice2:
        data = data.filter(datumObjave__year=2019)
    return render(request, 'filtar.html', {'data': data})

请注意,在您尝试访问查询之前(即直到您呈现html之前),它实际上不会执行查询。

另外,我建议您将此表单切换为django表单,如下所示:

forms.py:

class ChoiceForm(forms.Form):
    filter = forms.MultipleChoiceField(choices=(('Choice 1', 'Choice 1'), ('Choice 2', 'Choice 2')), widget=forms.CheckboxSelectMultiple)

views.py:

def filtar(request):
    form = ChoiceForm(request.GET or None)
    data = Clanak.objects.all()    
    if form.is_valid():
        if 'Choice 1' in form.cleaned_data['filter']:
            data = data.filter(naslov='NAME')
        if 'Choice 2' in form.cleaned_data['filter']:
            data = data.filter(datumObjave__year=2019)
    return render(request, 'filtar.html', {'data': data, 'form': form})

footer.html:

<br>
    <div>Filter: </div>
    <form>
      {% csrf_token %}
      <fieldset>
        <legend>Filtar - Thing that is being chosen</legend>

        {{ form.as_p }}

        <input type="submit" value="Submit">
      </fieldset>
    </form>
    <br>
    <div>Copyright by </div>