I have a ListView
to render page with table of objects. The first column are checkboxes to perform some actions on multiple objects (not a formset). Each checkbox contains an object id
as value
and utilizing AJAX requests to perform such actions.
There is no issues with direct POST
request as I send bunch of ids
in array, validate them through the form and update()
.
However I’m experiencing some difficulties with GET
request which suppose to be simplier:
I have a view to edit object (FBV). The goal is to redirect to that view with field contains all those ids
checked on ListView
. But I just came to know that I can’t call render()
after AJAX call so I’m wondering what is the right way to handle such a redirect passing initial
data to form presents in that view’s context.
Simplified code:
class ProducutsListView(ListView):
model = models.Product
template_name = "production/products_list.html"
paginate_by = 50
The view to redirect to:
def product_update_view(request):
if request.method == "POST":
form = forms.ProductUpdateForm(
request.POST,
)
products = form.cleaned_data["products"]
-------------------------------------
# some more validated data extracting
-------------------------------------
products.update(**fields)
return redirect("products_list")
else:
form = forms.ProductUpdateForm()
if is_ajax(request):
products_form = forms.ProductsMultipleForm(request.GET) # form contains only one field "poducts" represents an array of objects
if products_form.is_valid():
products = products_form.cleaned_data["products"]
form = forms.ProductUpdateForm(
initial={"products": products}
)
**# how to render a page with form contains `init` data?**
return render(request, "production/product_update.html", {"form": form})
JS / AJAX:
// there are multiple Map() objects each contains **view url**, **button** triggers request and **method** of request.
var $buttonsList = [asTested, setOnStock, configChange];
$.each($buttonsList, function () {
var $url = this.get("url");
var $btn = this.get("btn");
var $method = this.get("method");
$btn.on("click", function () {
$.ajax({
type: $method,
headers: $method == "POST" ? { "X-CSRFToken": CSRF } : {},
url: $url,
dataType: "json",
traditional : true,
data: {"products": getProductIds()},
success: function (response) {
if ($method == "POST") {
location.reload();
};
},
});