Remove fields from ModelForm

前端 未结 5 975
忘掉有多难
忘掉有多难 2020-12-09 06:16

i have a simple ModelForm:

class MyForm(ModelForm):

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        d         


        
相关标签:
5条回答
  • 2020-12-09 06:26

    As described in Creating forms from models - Selecting the fields to use, there are three ways:

    1. In the model, set editable=False. All forms created from the model will exclude the field.
    2. Define the fields attribute in the Meta inner class to only include the fields you want.
    3. Define the exclude attribute in the Meta inner class to list the fields you don't want.

    So if your model has fields field1, field2, and field3 and you don't want field3, technique #2 would look like this:

    class MyModelForm(ModelForm):
        class Meta:
            model = MyModel
            fields = ('field1', 'field2')
    

    And technique #3 would look like this:

    class MyModelForm(ModelForm):
        class Meta:
            model = MyModel
            exclude = ('field3',)
    
    0 讨论(0)
  • 2020-12-09 06:30

    I had the same problem. This is how I made it work in the new Django (trunk):

    class MyModelAdmin(admin.ModelAdmin):
        # Your stuff here..
    
        def get_form(self, request, obj=None, **kwargs):
            if request.user.is_staff: # condition
                self.exclude = ('field',)
            return super(PublishAdmin, self).get_form(request, obj=obj, **kwargs)
    

    By overriding the get_form method and putting the logic here you can select which Form you want to have displayed. Above I have displayed the standard form when a condition was met.

    0 讨论(0)
  • 2020-12-09 06:35

    One cause I can think of is if your ModelAdmin class which uses your custom form has conflicting settings. For example if you have also explicitly specified 'name' field within 'fields' or 'fieldsets' of your ModelAdmin.

    0 讨论(0)
  • 2020-12-09 06:39

    This works great...

    def __init__(self, instance, *args, **kwargs):    
        super(FormClass, self).__init__(instance=instance, *args, **kwargs)
        if instance and instance.item:
            del self.fields['field_for_item']
    
    0 讨论(0)
  • 2020-12-09 06:43

    You can use the exclude property to remove fields from a ModelForm

    exclude = ('field_name1', 'field_name2,)
    
    0 讨论(0)
提交回复
热议问题