View how to control what is in queryset from html control

Hello!

I want somehow filter with control on html page what is in queryset for my view

My model

class Production(models.Model):
    '''Выработка.'''
    project = models.ForeignKey(
        Project, on_delete=models.PROTECT, verbose_name='проект')
    timeperiod = models.ForeignKey(
        Timeperiod, on_delete=models.PROTECT, verbose_name='период')
    time = models.DurationField('трудочасы')
    ammount = models.DecimalField('выработка', max_digits=10, decimal_places=2)
    is_auto = models.BooleanField(
        'признак автоматического расчета', default=False)

My view

class Production(LoginRequiredMixin, ListView):
    login_url = reverse_lazy('collector:login')
    queryset = Production.objects.filter(project__title__contains=‘MYPARAM')
    context_object_name = 'productions'
    template_name = 'collector/production.html'

What i would like to achieve is on my attached picture

But I’m struggling

Do you want that select field to call your view with that value to pass as a parameter? You can do that in JavaScript, catching the on_change event for that select box.

If you want that selector to change what’s currently displayed without fetching data from the server, then that all needs to be done within JavaScript. (You’ll also be catching the on_change event, but now it becomes your responsibility to write the JavaScript code to show or hide the data to be displayed.)

Thank you for your answer!

For the history - I was able to achieve this without JS at all (but in such clean way as I desire - there is refresh for all page). Please, criticise this approach.

Here is example of concept:

Model

class TestModel(models.Model):
    title = models.CharField(’title', max_length=50)
    number = models.PositiveIntegerField(’number')

View

class TestView(ListView):
    template_name = 'collector/test.html'
    model = TestModel
    context_object_name = 'data'

    def get_queryset(self) -> QuerySet:
        title_id = self.request.GET.get('title')
        return TestModel.objects.filter(id=title_id)

    def get_context_data(self, **kwargs) -> Dict:
        context = super().get_context_data(**kwargs)
        context['titles'] = TestModel.objects.all()
        return context

Template

<form method="get">
  <select class="form-select" name="title">
    {% for title in titles %}
    <option value = "{{ title.id }}" {% if request.GET.title|add:"0" == title.id|add:"0" %}selected{% endif %}>{{ title.title }}</option>
    {% endfor %}
  </select>
  <button type="submit" class="btn">Фильтровать</button>
<form>
<table class="table">
  <thead>
    <tr>
      <th>id</th>
      <th>number</th>
    </tr>
  </thead>
  <tbody>
    {% for d in data %}
    <tr>
      <td>{{ d.title}} </td>
      <td>{{ d.number }}</td>
    </tr>
    {% endfor %}
  </tbody>
</table>

model

class Company(models.Model):
    code = models.CharField(max_length=25, unique=True)
    name = models.CharField(max_length=255, null=True, blank=True)
    
class Service(models.Model):
    code = models.CharField(max_length=25,unique=True, null=True, blank=True)
    name = models.CharField(max_length=255)
    unit_price = models.IntegerField()

    def __str__(self):
        return self.name
class ServiceCompany(models.Model):
    company = models.ForeignKey(Company, on_delete=models.SET_NULL, null=True)
    service = models.ForeignKey(Service, on_delete=models.SET_NULL, null=True)
    qty = models.IntegerField()
    
    def __str__(self):
        return self.company.name

view

@login_required
def report(request):
    services = Service.objects.all()
    companies = Company.objects.all()
    code = request.GET.get('code')
    company = Company.objects.get(code=code)
    services_used = ServiceCompany.objects.filter(company=company)
    return render(request, "export_data.html", {"services": services, 'company_list': companies, 'code': code, "services_used":(services_used)})

template

 <script type="text/javascript">
    const services = "{{services_used}}";
    
    console.log(services);
</script>

How do i set value of queryset from views.py to variable in javascript?

See the json_script tag.

1 Like

i found answer which i need in Django docs. Thank you very much!