Django: using 'can_order' to change order of forms in FormSet

余生长醉 提交于 2019-12-24 12:35:19

问题


I have a form with one field that keeps only the name of family members. I want user be able to change the order as the user wishes.

The current order is the order of their creation. I found the flag can_order for my formset; when I add it to my formset, another field appeared besides the names and that field is an integer showing the number in the list.

class FamilyMemebrsNameForm(forms.Form):
    name= forms.CharField(label=_('name'), max_length=250)

FamilyMemberNameItem = formset_factory(
    FamilyMemebrsNameForm, can_delete=True, can_order=True)

My question is: can I change the order of the forms (the names of family members) by playing with this number? If yes, how should I do that?


回答1:


Yes, by specifying can_order=True in you formset_factory, the additional field named form-N-ORDER can be used to define the order of the forms.

As the example from the link shows, you simply have to submit the new values for the order field and the ou can use iterate over the forms in order using formset.ordered_forms.

For example:

FamilyMemberFormset = formset_factory(
    FamilyMemebrsNameForm, can_delete=True, can_order=True)
formset = FamilyMemberFormset(request.POST)

if formset.is_valid():
    for form in formset.ordered_forms:
        print(form.cleaned_data)
        form.save()

BUT: if you want to store the order in the database, you need to define a new field in you model and store the order in that. The order of formsets is only present inside a single request/response, after that its gone.



来源:https://stackoverflow.com/questions/47494507/django-using-can-order-to-change-order-of-forms-in-formset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!