如何使Djangofilter不覆盖get参数

2024-06-16 18:05:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用django-tables2和django过滤器。加载页面的URL看起来像http://localhost:8000/pleasehelp/?param=abc。我需要参数值来加载页面。我使用的过滤器如下所示:

class MyFilter(django_filters.FilterSet):
    class Meta:
        model = MyModel
        fields = {
            'name': ['icontains'],
            'city': ['icontains'],
        }

这与简单模型有关:

class MyModel(models.Model):
    name = models.CharField(max_length=20)
    city = models.CharField(max_length=20)

我还创建了一个简单视图,其中包括:

class MyView(SingleTableMixin, FilterView):
    model = MyModel
    template_name = "pleasehelp/index.html"
    context_object_name = 'items'
    paginate_by = 25
    table_class = MyTable
    filterset_class = MyFilter

和一个表,包括:

class MyTable(tables.Table):
    extra_column = tables.Column(empty_values=())
    class Meta:
        model = MyModel
        template_name = "django_tables2/bootstrap4.html"
        fields = ('name', 'city', 'extra_column')

    def render_extra_column(self, record):
        """Render our custom distance column
        """
        param = self.request.GET.get('param', '')
        return param

最后,我的index.html如下所示:

{% load static %}
{% load render_table from django_tables2 %}
{% load bootstrap4 %}

{% block content %}
    {% if filter %}
        <form action="" method="get" class="form form-inline">
            {% bootstrap_form filter.form layout='inline' %}
            {% bootstrap_button 'filter' %}
        </form>
    {% endif %}
    {% if items %}
        {% render_table table %}
    {% else %}
        <p>No items were found</p>
    {% endif %}

    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <script src={% static 'site/javascript_helpers.js' %}></script>
{% endblock content %}%

我的问题是,当我尝试使用过滤器时,它会替换URL中的参数。Ie我的URL变成了http://localhost:8000/pleasehelp/?name__icontains=a&city__icontains=,而不是我想要的http://localhost:8000/pleasehelp/?name__icontains=a&city__icontains=&param=abc(注意,它有daya django过滤器需要的,还有我需要的数据)


Tags: djangonameformurl过滤器cityparamtable