0

I have in my views the following code:

def stato_patrimoniale(request):
    now=datetime.datetime.now()
    now=now.year
    ...
    if Ricavi.objects.count()>0:
            for year, month, totale in(Ricavi.objects.values_list( 'data_pagamento_acconto__year', 'data_pagamento_acconto__month').
                annotate(totale=ExpressionWrapper(Sum(F('acconto')),
                output_field=FloatField())).values_list('data_pagamento_acconto__year', 'data_pagamento_acconto__month', 'totale')):
                if id not in incassi.keys() and  year == now:
                    incassi[id]=list(defaults)
                index=month-1
                incassi[id][index]=totale

The now variable is used to filter my data in the queryset, where my ricavi is the following models:

class Ricavi(models.Model):
    codice_commessa=models.ForeignKey(Informazioni_Generali, on_delete=models.CASCADE, null=True, blank=True)
    # numero_lavorazione
    acconto=models.DecimalField()
    data_pagamento_acconto=models.DateField()

Now I want to replace the now variable witha a form that give me the possibility to choose the year and update my views.

I have created another app with the following model that with a form gives the possibility to add new year:

class Timing(models.Model):
    reference_year = models.DecimalField(max_digits=4, decimal_places=0, default="2020")

Now I want to create a dropdown button that contains all the reference_year filled and when the client click on one of them, the now variable in my def stato_patrimoniale(request): is updated. How could I get this aim?

4
  • why don't you post the year variable to use it in stato_patrimoniale ? Commented Jun 15, 2020 at 9:54
  • In which sense? Commented Jun 15, 2020 at 10:04
  • your want to update now variable and update your view. So post it to stato_patrimoniale when it changes then, update now and ... Commented Jun 15, 2020 at 10:54
  • look for the year in your request: request.POST['year'] Commented Jun 15, 2020 at 11:32

2 Answers 2

1

Insert the drop down in a form like :

<form method="POST" action="url to stato_patrimoniale">
{% csrf_token %}
<select name="year" id="year" onchange="this.form.submit()">
   <option value="2020">2020</option>
   <option value="2019">2019</option>
   <option value="2018">2018</option>  
</select>
</form>

then in stato_patrimoniale add :

 now = now.year
 if request.method == 'POST':
     year = request.POST['year']
     if year != '':
          now = year
Sign up to request clarification or add additional context in comments.

1 Comment

I believe he is looking for an Ajax request
0

i have this way to do code a views that receives an ajax request.

Note: ill show some example code because im too sleeply to work on an full example haha

Is not the most efficient way, but it works, also accept multiple parameters to filter or manipulate or do whatever you want.

def searchAjaxView(request):
    if request.method == "POST" and request.is_ajax:
        body = json.loads(request.body)
        requestData = {}
        for item in body:
            name = item['name']
            requestData[name] = item
   #all your logic goes here ... 
   #for example read the year
   #Important, check if it exist on the dict before trying to get the value OR always send a default value... in this case im working around the default option in select
   year= requestData['year']['value']
   if year !='':
      #ah idk do your stuff here with the year i'll return a json response
      product_list = list(MyTable.objects.all())
   data = serializers.serialize('json', product_list)
   return JsonResponse(data, safe=False)

Okay in the html-js i have this example with jquery. Works fine, again not the fanciest way.

<!-- no need ne method attrs, just declaratively -->
<form method="POST" id="filterForm" name="filterForm">{% csrf_token %}
 <select name="year" id="year" class="m-auto basic-single my-1 mr-sm-2">
 <option value="">Select a year</option>
<!-- at this point i'm copy-paste code from my project, ps: trick to lazy fill the select with years -->
 {% with ''|center:10 as range %}
 {% for _ in range reversed %}
 <option value="200{{ forloop.counter0 }}">200{{ forloop.counter0 }}</option>
 {% endfor %}
 {% endwith %}
 {% with ''|center:10 as range %}
 {% for _ in range reversed %}
 <option value="201{{ forloop.counter0 }}">201{{ forloop.counter0 }}</option>
 {% endfor %}
 {% endwith %}
 {% with ''|center:1 as range %}
 {% for _ in range reversed %}
 <option value="202{{ forloop.counter0 }}">202{{ forloop.counter0 }}</option>
 {% endfor %}
 {% endwith %}
 </select>
 <div class="form-group container my-1">
 <button class="col-12 form-control btn btn-success" type="sumbit">Filter</button>
 </div>
</form>

<script>
    var frm = $('#filterForm');
    frm.submit(getAjax);
    function getAjax() {
        var formData = JSON.stringify($("#filterForm").serializeArray());
        console.log("Request parameters:")
        console.log(JSON.parse(formData))
        $.ajax({
            headers: { "X-CSRFToken": '{{csrf_token}}' },
            type: "POST",
            url: "{% url 'publication:response' %}",
            contentType: 'application/json',
            dataType: 'json',
            data: formData,
            success: function (data) {
                jsonData = console.log(data);
                var dataObj = JSON.parse(data);
                console.log("Response data:")
                console.log(dataObj)
                //more stuff here, too much for this example
            },
        }); return false;
    }
</script>

If your project grows big and you are in the situation where you have to do many of this kinda-dynamically-update to your templates or so, consider using a front-end framework or javascript libraries. Better both.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.