Django forms, inheritance and order of form fields

前端 未结 11 1797
终归单人心
终归单人心 2020-12-12 12:15

I\'m using Django forms in my website and would like to control the order of the fields.

Here\'s how I define my forms:

class edit_form(forms.Form):
         


        
11条回答
  •  我在风中等你
    2020-12-12 12:53

    I used the solution posted by Selene but found that it removed all fields which weren't assigned to keyOrder. The form that I'm subclassing has a lot of fields so this didn't work very well for me. I coded up this function to solve the problem using akaihola's answer, but if you want it to work like Selene's all you need to do is set throw_away to True.

    def order_fields(form, field_list, throw_away=False):
        """
        Accepts a form and a list of dictionary keys which map to the
        form's fields. After running the form's fields list will begin
        with the fields in field_list. If throw_away is set to true only
        the fields in the field_list will remain in the form.
    
        example use:
        field_list = ['first_name', 'last_name']
        order_fields(self, field_list)
        """
        if throw_away:
            form.fields.keyOrder = field_list
        else:
            for field in field_list[::-1]:
                form.fields.insert(0, field, form.fields.pop(field))
    

    This is how I'm using it in my own code:

    class NestableCommentForm(ExtendedCommentSecurityForm):
        # TODO: Have min and max length be determined through settings.
        comment = forms.CharField(widget=forms.Textarea, max_length=100)
        parent_id = forms.IntegerField(widget=forms.HiddenInput, required=False)
    
        def __init__(self, *args, **kwargs):
            super(NestableCommentForm, self).__init__(*args, **kwargs)
            order_fields(self, ['comment', 'captcha'])
    

提交回复
热议问题