How to implement CRUD Using Ajax and Json - using a filtered list

(Kevin Damstra) #1

Hi there!

I’ve read your tutorial on using Ajax and Json to handle CRUD, CRUD with Ajax and Json

The tutorial is great but I’m running into a little issue, what if I’m using a filtered list? Let’s say I want to filter the list by “date_added”

#book_list.html

<!-- filter list on date -->
<form class="form-inline" id="filter_book_date_added" method="get">
    <input type="text" class="form-control" id="datepicker_book_filter" data-toggle="datetimepicker" data-target="#datepicker_book_filter" name="added_date">
    <button class="btn btn-primary" type="submit">Filter</button>
</form>

<!-- table list below -->

I would create the following listview:

class BookListView(ListView):
    context_object_name = 'book_list'
    model = Book
    template_name = 'book_list.html'

    def get_queryset(self):
	date_filter = self.request.GET.get('added_date')

	if date_filter:
		queryset = Book.objects.filter(date_added=date_filter)
	else:
		queryset = Book.objects.all()

	return queryset

Now if would create a new record we would update “books/includes/partial_book_list.html”, but this list contain all the books including the newly created book. However it doesn’t keep the filter.

Since the filter is a Get request, I’m not sure how I could filter the returned list.

The view below is used in the tutorial, before the list gets returned to the view I would like to filter it by the date filter above…

#views.py

def book_create(request):
data = dict()

if request.method == 'POST':
    form = BookForm(request.POST)
    if form.is_valid():
        form.save()
        data['form_is_valid'] = True
        books = Book.objects.all()
        # The line below updates the partial_book_list, how can we filter this before it gets send to the template?
        data['html_book_list'] = render_to_string('books/includes/partial_book_list.html', {
            'books': books
        })
    else:
        data['form_is_valid'] = False
else:
    form = BookForm()

context = {'form': form}
data['html_form'] = render_to_string('books/includes/partial_book_create.html',
    context,
    request=request
)
return JsonResponse(data)

With best regards,

Kevin

(Basil Jose) #2

Add a hidden input field in your form and place the get param value within it,

<input type="hidden" name="added_date" value="{{request.GET.added_date}}">

then in book_create access this value request.POST.get('added_date', None)