Передача переменных фильтра через URL и сохранение их через перенаправление - PullRequest
0 голосов
/ 01 мая 2019

У меня 2 проблемы:

  1. У меня есть перенаправление, которое возвращает к тому же шаблону, применен фильтр, который передает параметры следующим образом: http://localhost:99/depot/container/11/?area_easting=99&area_northing=&context_number=123&sample_number=&sample_type=organic.Когда я перенаправляю на тот же шаблон, параметры теряются (как и ожидалось), как мне перенаправить и сохранить эти параметры?Я также ожидаю, что мне понадобится кнопка «Обновить запрос».

  2. В шаблоне я могу передать операцию и sample_id, но не container_id.Это происходит из m2m samples = models.ManyToManyField('Sample', through='ContainerSamples'), как мне передать это значение в URL - связанном с пунктом 1.

Мой код

<a href="{ url 'depot:change_container'  operation='add' pk=sample.container.container_id fk=sample.sample_id }" class="badge badge-primary" role="button">
      <<
    </a>

# urls.py
path('container/<int:container_id>/', views.detailcontainer, name='detailcontainer'),

# views.py
def detailcontainer(request, container_id):
    container = get_object_or_404(Container, pk=container_id)
    samples = container.samples.all()
    container_contents = container.samples.all()
    unassigned_samples = Sample.objects.all()[:10]
    unassigned_samples2 = Sample.objects.all()

    qs = Sample.objects.all()
    easting_query = request.GET.get('area_easting')
    northing_query = request.GET.get('area_northing')
    context_query = request.GET.get('context_number')
    sample_number_query = request.GET.get('sample_number')
    sample_type_query = request.GET.get('sample_type')

    if easting_query != '' and easting_query is not None:
        qs = qs.filter(area_easting__icontains=easting_query)
    if northing_query != '' and northing_query is not None:
        qs = qs.filter(area_northing__icontains=northing_query)
    if context_query != '' and context_query is not None:
        qs = qs.filter(context_number__icontains=context_query)
    if sample_number_query != '' and sample_number_query is not None:
        qs = qs.filter(sample_number__icontains=sample_number_query)
    if sample_type_query != '' and sample_type_query is not None:
        qs = qs.filter(sample_type__icontains=sample_type_query)

    context = {
        'queryset': qs,
        'container':container,
        'container_contents': container_contents,
        'unassigned_samples': unassigned_samples,
    }
    return render(request, 'container/detailcontainer.html', context)

# template
      {% for sample in queryset %}
      <tr>
        <td><a href="{ url 'depot:change_container'  operation='add' pk=sample.container.container_id fk=sample.sample_id }" class="badge badge-primary" role="button">
          <<
        </a></td>
        <td>{{ sample.sample_id }}</td>
        <td>{{ sample.samples.container.container_id }}</td>
        <td>{{ sample.area_easting }}.{{ sample.area_northing }}.{{ sample.context_number }}.{{ sample.sample_number }}</td>

        <td>
  {{ sample.sample_type }}
        </td>

        <td>{{ sample.taken_by }}</td>

      </tr>
      {% empty %}
      <tr>
        <td colspan="5">No data</td>
      </tr>
      {% endfor %}

РЕДАКТИРОВАТЬ

Операция обрабатывается с помощью этого кода:

def change_container(request, operation, pk='', fk=''):
    container = Container.objects.get(pk=pk)
    sample = Sample.objects.get(pk=fk)

    if operation == 'add':
        ContainerSamples.add_to_container(container, sample)
    elif operation == 'remove':
        ContainerSamples.remove_from_container(container, sample)
    # return redirect('depot:allcontainer')

    return redirect('depot:detailcontainer', container_id=pk) 

1 Ответ

0 голосов
/ 01 мая 2019

Ваш URL-путь просто принимает container_id, поэтому вы не сможете передать те значения, которые вы хотите, в качестве URL-параметров. Либо вам нужно изменить путь URL-адреса, либо продолжать передавать их в виде строк запроса, что, я полагаю, именно этого вы и хотите.

Чтобы передать их в виде строк запроса, вам необходимо включить все request.GET.get('qs'), которые вы собираете в своем представлении, в свой контекст, и они будут доступны в шаблоне.

    context = {
        'queryset': qs,
        'container':container,
        'container_contents': container_contents,
        'unassigned_samples': unassigned_samples,
        'easting_query': easting_query,
        'northing_query': northing_query,
        'context_query': context_query,
        'sample_number_query': sample_number_query,
        'sample_type_query': sample_type_query
    }

Затем в вашем шаблоне вы передаете их в тег URL.

<td><a href="{% url 'depot:change_container' container.container_id %}?operation=add&foo=bar&blabla=123" class="badge badge-primary" role="button">

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...