1

I am using Django filter and using it in normal view it is working as expected now I want to download the filtered data so for this I am writing one download view where I am trying to use the same FilterClass but no luck. It is giving me an ERROR(Exception Value:
type object 'CTSFilter' has no attribute 'values_list'
). Can anyone please help/suggest how to use filtered queryset in filter class more than one view OR pass the data of filtered query to the download views.

Please find my code.

filters.py

class CTAFilter(django_filters.FilterSet):
    id = django_filters.NumberFilter(label="DSID")
    class Meta:
        model = CTA
        fields = ['id', 'EmailID','id','Shift_timing']

Here I want when the user will select Shift_timing for example Morning he will get 10 records so the same data I want to pass to the below download view. (For this I am using CTSFilter class but no luck.)

Please find the below download code(View).

def exportcts_data(request):
    response = HttpResponse(content_type='application/ms-excel')
    response['Content-Disposition'] = 'attachment; filename="CTA_ShiftTiming.xls"'
    wb = xlwt.Workbook(encoding='utf-8')
    ws = wb.add_sheet('CTS_ShiftChange Data') # this will make a sheet named Users Data
    # Sheet header, first row
    row_num = 0
    font_style = xlwt.XFStyle()
    font_style.font.bold = True
    columns = ['id','idk','Shift_timing','EmailID','Vendor_Company','Project_name','SerialNumber','Reason','last_updated_time']
    for col_num in range(len(columns)):
        ws.write(row_num, col_num, columns[col_num], font_style) # at 0 row 0 column
    # Sheet body, remaining rows
    font_style = xlwt.XFStyle()
    # cts_list = CTA.objects.all()
    # cts_filter = CTAFilter(request.GET, queryset=cts_list)
    # allcts = cts_filter.qs
    rows = CTAFilter.values_list('id', 'idk', 'Shift_timing', 'EmailID', 'Vendor_Company', 'Project_name',
                              'SerialNumber', 'Reason', 'last_updated_time')
    for row in rows:
        row_num += 1
        for col_num in range(len(row)):
            ws.write(row_num, col_num, row[col_num], font_style)
    wb.save(response)
    return response

Note: If I am Hardcoding it it is working for example.

 rows = `TCA.objects.filter(Shift_timing__exact='Morning').values_list('id','idk','Shift_timing','EmailID','Vendor_Company','Project_name','SerialNumber','Reason','last_updated_time')`

so above code give me all result where Shift timing is morning but I want to do it dynamically bypassing filtered class data. Any help on this would be highly appreciable.

+Adding my View(render which is showing page content)

  def retrievecta_view(request):
        if request.method == 'GET':
            allcta = CTA.objects.all()
            allcta1 = allcta
            allctagen = allcta1.filter(Shift_timing__exact='General')
            allctamor = allcta1.filter(Shift_timing__exact='Morning')
            allctseve = allcta1.filter(Shift_timing__exact='Evening')
            allctatotal = allcta1.filter(Shift_timing__exact='Total')
    
            # For filtering using   'django_filters',
            cta_list = CTA.objects.all()
            cta_filter = CTAFilter(request.GET, queryset=cta_list)
            allcta = cta_filter.qs
    
            paginator = Paginator(allcta, 50)
            page_number = request.GET.get('page')
            try:
                allcts = paginator.page(page_number)
            except PageNotAnInteger:
                allcts = paginator.page(1)
            except EmptyPage:
                allcts = paginator.page(paginator.num_pages)
            return render(request, 'abcd/cta.html', {'allcta': allcta, 'cta_filter': cta_filter, 'allcta1': allcta1,
                                                      'allctagen': allctagen, 'allctamor': allctamor,
                                                      'allctaeve': allctaeve,
                                                      'allctatotal': allctatotal})

Note: If I will keep my same URL (retrievecta_view)then download view is working but separately it is not working.

@register.simple_tag
def relative_url(value, field_name, urlencode=None):
    url = '?{}={}'.format(field_name, value)
    if urlencode:
        querystring = urlencode.split('&')
        filtered_querystring = filter(lambda p: p.split('=')[0] != field_name, querystring)
        encoded_querystring = '&'.join(filtered_querystring)
        url = '{}&{}'.format(url, encoded_querystring)
    return URL

Code I am using for pagination and returning filter querystring.

{% load apple_extras%}


{% if page.has_other_pages %}
  <ul class="pagination">
    {% if page.has_previous %}
      <li class="disabled"><a href="?page={{ page.previous_page_number }}">&laquo;</a></li>
    {% else %}
      <li class="disabled"><span>&laquo;</span></li>
    {% endif %}


    {% for i in page.paginator.page_range %}
      {% if page.number == i %}
        <li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li>
      {% else %}
      <li>
      <a href="{% relative_url i 'page' request.GET.urlencode %}">{{ i }}</a>
    </li>
      {% endif %}
    {% endfor %}
    

    {% if page.has_next %}
      <li class="disabled"><a href="?page={{ page.next_page_number }}">&raquo;</a></li>
    {% else %}
      <li class="disabled"><span>&raquo;</span></li>
    {% endif %}
  </ul>
{% endif %}
Shailesh Yadav
  • 301
  • 2
  • 16
  • Can you sure the querystring of the URL that you're expecting the filtered data and getting all data? – schillingt Dec 23 '20 at 13:56
  • Hi @schillingt, I have updated the code that I am using for querystring of the URL. How to use this in download views? – Shailesh Yadav Dec 23 '20 at 14:24
  • If I am using the same download view inside FBV I could see only is working as both (displaying content and downloading filtered data view are GET method).facing this problem.https://stackoverflow.com/questions/65391528/how-to-handle-to-get-request-in-in-same-fbvfunction-based-view – Shailesh Yadav Dec 23 '20 at 14:45
  • Can you verify that `request.GET` has the values you expect for the download view? – schillingt Dec 23 '20 at 15:47
  • Thanks @schillingt I have Checked and getting below result. print('Download View ',request.GET) giving me empty queryset output : Download View I have tried like this: cts_filter = CTSFilter(request.GET.urlencode, queryset=cts_list) but getting Exception Type: AttributeError Exception Value: 'function' object has no attribute 'get' How to get the same URL which I am getting after applying filter(calling relative_url method)? – Shailesh Yadav Dec 23 '20 at 16:45
  • The problem is that the url for the Download view is missing the querystring parameters which results in `request.GET == {}` which means none of your filters are used. – schillingt Dec 23 '20 at 16:47
  • How to get the same filter URL for download view? – Shailesh Yadav Dec 23 '20 at 16:49
  • 1
    It depends on how your application functions. You may need to regenerate the url similar to how you do it in `relative_url`, or you could copy the querystring from the request for the filtered view and add that to the download url. There's no clear cut answer here because it depends on your application and how it works. However, I think you have enough information to be able to implement this. – schillingt Dec 23 '20 at 17:34
  • Thank you very much for your time. I will try and implement it. – Shailesh Yadav Dec 23 '20 at 17:42
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/226369/discussion-between-shailesh-yadav-and-schillingt). – Shailesh Yadav Dec 24 '20 at 04:53
  • Hi @schillingt, How to copy query string from the request of filtered view and use inside download view. In my application user will search results based on fields = ['id', 'EmailID','id','Shift_timing'] and then displayed the record I want to download.In the case of a normal view, I am using it inside HTML pagination.html template how to reuse/write it inside the download function. Thank you! – Shailesh Yadav Dec 24 '20 at 05:03
  • Here's a SO answer: https://stackoverflow.com/a/6454045/1637351 – schillingt Dec 24 '20 at 16:07
  • Hi @schillingt, Thank you Very Much. It is working as expected. – Shailesh Yadav Dec 28 '20 at 17:28
  • Glad to hear it! – schillingt Dec 28 '20 at 18:31

0 Answers0