django形成了设置字段顺序

时间:2014-12-18 20:47:48

标签: django forms field

我正在尝试设置表单的fieldorder。但不知何故,它只是按字母顺序排列。有人有什么建议吗?我尝试了Meta:fields = [" field"," field"]并在 init

中添加了keyOrder

形式:

class HangarFilterForm(forms.Form):

    FIELDS = [
        ("", ""),
        ("warp", "Warp"),
        ("cargo_space", "Cargo Space"),
        ("smuggle_bay", "Smuggle Bay"),
        ("dock", "Dock/Undock"),
        ("enter_warp", "Enter Warp"),
        ("fuel_bay", "Fuel Bay"),
        ("fuel_cost", "Fuel Cost"),
    ]

    PER_PAGE = [
        (10, ""),
        (5, "5 ships"),
        (10, "10 ships"),
        (25, "25 ships"),
        (50, "50 ships"),
    ]

    field_1 = forms.ChoiceField(choices=FIELDS, label="1st attribute", required=False)
    field_2 = forms.ChoiceField(choices=FIELDS, label="2nd attribute", required=False)
    per_page = forms.ChoiceField(choices=PER_PAGE, required=False)

    def __init__(self, *args, **kwargs):
        super(HangarFilterForm, self).__init__(*args, **kwargs)
        self.fields['planet'] = forms.ChoiceField(
                        choices=[("", "")] + [ (o.id, o.name) for o in    lanet.objects.all().order_by("name")], 
                        required=False)
        self.fields['type'] = forms.ChoiceField(
                        choices=[("", "")] + [ (o[0], o[1]) for o in ShipTemplate.SHIP_TYPES], required=False)
        self.fields.keyOrder = ["planet", "type", "field_1", "field_2", "per_page"]

5 个答案:

答案 0 :(得分:4)

在Django 1.9中,添加了强制表单字段顺序的新方法:from django.db import models class Project(models.Model): end_date = models.DateField(verbose_name='End date', blank=True) start_date = models.DateField(verbose_name='Start date', blank=True) title = models.CharField(max_length=255, blank=False, verbose_name='Title') def __str__(self): return self.title

看一下(链接到1.9版): https://docs.djangoproject.com/en/1.9/ref/forms/api/#django.forms.Form.field_order

(和dev版本的链接): https://docs.djangoproject.com/en/dev/ref/forms/api/#django.forms.Form.field_order

在下面找一个简短的例子(使用Django 1.9)

models.py:

from django.forms import ModelForm, DateTimeField, SelectDateWidget

from XXX.models import Project

class ProjectForm(ModelForm):
    class Meta:
        model = Project
        fields = '__all__'

    start_date = DateTimeField(widget=SelectDateWidget)
    end_date = DateTimeField(widget=SelectDateWidget)

    field_order = ['start_date', 'end_date']

forms.py

{{1}}

在此示例中,字段将重新排列为:

  1. start_date< ==使用表单类
  2. 中的列表
  3. end_date< ==使用表单类
  4. 中的列表
  5. title< ==未在列表中提及,因此使用默认排序

答案 1 :(得分:3)

我尝试在django 2.1的$('#iBarcode').keypress(function (keyPressed) { if (keyPressed.which == 13) { var barcode = $('#iBarcode').val() var splitted = new Array() var arrayCnt = -1; for (var i = 0; i < barcode.length; i++) { var flagStart; if (barcode.charAt(i) == ')') { flagStart = true i += 1 arrayCnt += 1 splitted[arrayCnt] = '' } if (barcode.charAt(i) == ('(')) { flagStart = false } if (flagStart == true) { splitted[arrayCnt] = splitted[arrayCnt] + barcode.charAt(i) } } console.log(setMatDesc(splitted[0])) //value showed here splitted[arrayCnt + 1] = setMatDesc(splitted[0]) //value not showed here and skipped? splitted[arrayCnt + 1] = currentDate $('#iBarcode').val('').focus console.log(splitted) } }) function setMatDesc(MatID) { var result $.ajax({ url: '@Url.Action("Get_MatDesc")', type: 'GET', async: false, data: { MatID: MatID }, success: function (data) { result=data }, error: function (xhr) { alert('error'); } }) return result } 表单的一部分中设置fields,而且还成功了:

Meta

答案 2 :(得分:1)

这是我过去做过的一些代码,用于重新排列有效的表单中的字段顺序;你可以将它放入mixin以供其他地方使用。让我知道它是怎么回事。

from django.utils.datastructures import SortedDict


class HangarFilterForm(forms.Form):

    ordered_field_names = ['planet', 'type', 'field_1', 'field_2', 'per_page']

    def __init__(self, *args, **kwargs):
        super(HangarFilterForm, self).__init__(*args, **kwargs)
        # Your field initialisation code
        self.rearrange_field_order()

    def rearrange_field_order(self):

        original_fields = self.fields
        new_fields = SortedDict()

        for field_name in self.ordered_field_names:
            field = original_fields.get(field_name)
            if field:
                new_fields[field_name] = field

        self.fields = new_fields

如果您出于某种原因想要跟踪原始文件订单,只需将original_fields更改为self.original_fields中的rearrange_field_order

答案 3 :(得分:1)

可能有点偏离主题。使用django crispy formstheir Layout objects可以帮助您完全按照自己的方式进行格式化。其中包括重新排列字段顺序。

示例说明:

class UpdateUserForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.layout = Layout(
            Field('email'),
            Field('quote'),
            Field('website', placeholder="http://"),
            Field('logo', template="user/logoInput.html"),
            HTML('<label class="control-label">Other settings</label>'),
            Field('emailVisible'),
            Field('subscribeToEmails'),
            Field('mpEmailNotif'),
            Field('showSmileys'),
            Field('fullscreen'),
        )

    class Meta:
        model = ForumUser
        fields = ('email', 'emailVisible', 'subscribeToEmails', 'mpEmailNotif',
                  'logo', 'quote', 'website', 'showSmileys', 'fullscreen')

答案 4 :(得分:0)

我使用 bspink 的方式进行了一些更改。 (在 Python 3.7+ 上使用)(https://stackoverflow.com/a/39980744/14506165)

class SomeForm(forms.Form):
    # define only you want to put top, no need to define all of them
    # unless you need more specific ordering        
    ordered_field_names = ['planet', 'type']

    def __init__(self, *args, **kwargs):
        super(SomeForm, self).__init__(*args, **kwargs)
        # call initialization code
        self.rearrange_field_order()

    def rearrange_field_order(self):
        # add defined fields first 
        new_fields = {field_name: self.fields.get(field_name) for field_name in self.ordered_field_names}

        # then add others whose not defined in order list
        for key, value in self.fields.items():
            if key not in new_fields:
                new_fields[key] = value

        self.fields = new_fields