Django:使用“ can_order”更改FormSet中表单的顺序 [英] Django: using 'can_order' to change order of forms in FormSet

查看:79
本文介绍了Django:使用“ can_order”更改FormSet中表单的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表单,其中一个字段仅保留家庭成员的名称。我希望用户能够按照用户的意愿更改顺序。

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.

当前订单是其创建的顺序。我在表单集中找到了 can_order 标记;当我将其添加到表单集中时,名称旁边会出现另一个字段,并且该字段是显示列表中数字的整数。

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?

推荐答案

是,通过指定 can_order = True 在您 formset_factory ,另外一个名为 form-N-ORDER 的字段可用于定义表单的顺序。

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.

如链接中的示例所示,您只需要提交order字段的新值,并且ou可以使用 formset对表单进行迭代。

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.

例如:

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.

这篇关于Django:使用“ can_order”更改FormSet中表单的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆