Hello,
I try to get value from formset, but I get an empty dict…
views.py
class CmsView(ListView):
queryset = Cmsexport.objects.all().values()
model = Cmsexport
form_class = CmsFilterForm
template_name = 'table.html'
context_object_name = 'table'
paginate_by = 10
def get_queryset(self):
queryset = super(CmsView, self).get_queryset()
field = self.request.GET.get('field')
lookup = self.request.GET.get('lookup')
value = self.request.GET.get('value')
reset = self.request.GET.get('btn-reset')
formset = CmsFormSet(self.request.GET)
if formset.is_valid():
for f in formset:
print(f.cleaned_data)
if (field and lookup and value) is not None:
query = field.lower().replace(" ", "_") + '__' + lookup
queryset = Cmsexport.objects.filter(**{ query: value }).values()
if reset:
queryset = Cmsexport.objects.filter().values()
return queryset
def get_context_data(self, **kwargs):
context = super(CmsView, self).get_context_data(**kwargs)
#context['form'] = CmsFilterForm()
context['formset'] = CmsFormSet(queryset=Cmsexport.objects.none())
return context
forms.py
from django import forms
from django.forms import ModelForm, modelformset_factory
from .models import (
Cmsexport,
Dns,
Alias,
Sectools,
)
class CmsFilterForm(ModelForm):
class Meta:
model = Cmsexport
fields = '__all__'
CmsFormSet = modelformset_factory(
Cmsexport,
fields='__all__',
extra=2,
can_delete=True,
)
template.py
{% block content %}
<div class="accordion" id="accordionExample">
<div class="accordion-item">
<h2 class="accordion-header">
<button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
Filter
</button>
</h2>
<div id="collapseOne" class="accordion-collapse collapse" data-bs-parent="#accordionExample">
<div class="accordion-body">
<form id="form-container" method="GET">
{{ formset.management_form }}
<table>
{% for form in formset %}
<div class="table-form">
<label for="Field">Field </label>
<select name="field" class="form-control">
{% for field in form %}
<option value="{{field.label}}">{{field.label}}</option>
{% endfor %}
</select>
<label for="lookup">Lookup </label>
<select name="lookup" class="form-control">
<option value="iexact">iexact</option>
<option value="icontains">icontains</option>
<option value="in">in</option>
</select>
<label for="value">Value </label>
<input id="value" type="text" name="value" value="{{ current_value }}">
</div>
{% endfor %}
</table>
<button id="add-form" type="button" class="btn btn-primary">Add form</button>
<button type="submit" class="btn btn-primary">Search</button>
<button type="submit" name="btn-reset" class="btn btn-secondary" value="btn-reset">Reset</button>
</form>
</div>
</div>
</div>
</div>
output:
[15/Sep/2023 08:27:46] "GET /cms/ HTTP/1.1" 200 142477
{}
{}
[15/Sep/2023 08:27:51] "GET /cms/?form-TOTAL_FORMS=2&form-INITIAL_FORMS=0&form-MIN_NUM_FORMS=0&form-MAX_NUM_FORMS=1000&field=Name&lookup=iexact&value=&field=Name&lookup=iexact&value= HTTP/1.1" 200 9463