Home > Mobile >  What Is Can Order In Django Formsets Actually For?
What Is Can Order In Django Formsets Actually For?

Time:02-11

I've spent a fair amount of time the last day or so exploring the can order field with Django Formsets but I can't for the life of me actually figure out what it's for. Apparently it doesn't update the database...and it does put an order number field with the form....but beyond that what is it for?

I can't find any useful documentation on how to actually use this field. Do I have to write Javascript in order to get this field to do anything actually meaningful?

I get the delete option...and you have to add code in to delete the record...So I guess I'm to take it the same is required for the can_order field?

Sorry if this is a silly question but I've spent more time trying to figure this out than what would be reasonable by now.

CodePudding user response:

All it does is add an integer ORDER field to each form in the formset so you can manually order them after instantiating the formset. Just imagine your forms have a title with this imaginary formset data. You can use ordered_forms to iterate through each form, inspect its cleaned_data, and change it's ordering before returning the form in your context.

formset = ArticleFormSet(data)

if formset.is_valid():
    for form in formset.ordered_forms:
        if form.cleaned_data['title'] = 'My form title'
            form.cleaned_data['ORDER'] = 2
            form.save()

CodePudding user response:

The can_order adds a field to the formset, just like the can_delete does. You do not NEED JavaScript, but you can use it, for example if you use JavaScript to drag and drop the forms in the formset. You can sort them and then you can change the name attribute to reflect the new order by accessing the specific form by using it's id in your JavaScript.

The can_order IS like the can_delete, in that the can_order` will simply add the following to each of the forms in your formset, where N = 0, 1, 2, 3, 4...

<input type="number" name="form-N-ORDER" id="id_form-N-ORDER">

What can you do with this without JavaScript? Add an order field to your model, and then you can get the forms order in your post, and set the order field of your model to equal that.

  • Related