I have a ListView that displays every customer (class Cliente in my code) of a company. Every Cliente object has a specific id (piva in my code) that is necessary to make a third party API call. My goal was to press a button in the template that makes an API call for every Cliente object in my ListView queryset.

To accomplish this I overwrite the get_context_data method in the ListView to include a tuple of piva:

def get_context_data(self, *, object_list=None, **kwargs):
    ctx = super().get_context_data()
    pive = pive_extraction(self.get_queryset())  # pive_extraction(qs: QuerySet[Cliente]) -> tuple[str]
    ctx['pive'] = pive
    return ctx

In my ListView template I have this form:

<form action="{% url 'crm:cerved-multiple-api-call' %}" method="POST">
    {% csrf_token %}
    <input hidden name="ricerca" id="ricerca" value="{{pive}}">
    <button>Arricchimento Cerved di tutti i clienti</button>

Pressing the button perform the action on this view:

def cerved_multiple_api_call_view(request):
    if request.POST:
        pive = eval(request.POST['ricerca'])
        for piva in pive:
            data = cerved_api_call(piva) # third party API call
            # some non-relevant code where I work with 'data'

        return redirect('crm:cliente-list')

The code works fine and an API call is done for every Cliente in my ListView queryset; But inserting a tuple of piva ids in the context, pass it as request.POST data, getting it eval() back into a tuple[str] (because it becomes a single str when passed in request.POST) and then performing an API call for every 'str' in my tuple smells like bad code. Any response is appreciated.



Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.