Why does my excluded field still appear in this Django form?

纵然是瞬间 提交于 2021-02-07 05:21:11

问题


I'm using exclude in my form's Meta class to exclude a field from my form that I want to fill in programatically, but it's still showing up in the form.

Here are some excerpts from the code:

# Model
class Info(models.Model):
    completed_by = models.ForeignKey(User, related_name='+')

# Form
class InfoForm(forms.ModelForm):
    class Meta:
        model = Info
        exclude = ('created_by',)  #ETA: added comma to make this a tuple
        widgets = {
            'some_other_field': forms.HiddenInput(),
            'some_other_field2': forms.DateInput(attrs={'readonly': True}),
        }

# View
form = InfoForm(initial={'some_other_field': value}, 
                          prefix='info', instance=info)
return direct_to_template(request, 'myapp/info.html', locals())

# Template
<form class='uniForm' method='POST'>
{% csrf_token %}
<fieldset class='inlineLabels'>{{ form|as_uni_form }}</fieldset>
<input type='submit' name='action' value='Save' />
</form>

This seems like it should be pretty simple, and I know I've done it successfully before. I've deleted/recreated my DB and cleared my browser cache, just to be sure that's not a factor. I also tried making it a HiddenInput field, just like some_other_field (which is a ForeignKey field also), but it still shows up on the form.

Is there something here I'm missing? Is uni_form overriding the setting somehow? If not, any advice as to what I might look for in debug to see where/why this is happening?

(Using Django version 1.2.7)


回答1:


exclude needs a tuple, so you need

# note the extra comma
exclude = ('created_by',)

django iterates through the exclude, and since strings are iterable (return each character) this doesn't throw an error




回答2:


For older Django versions, there's a problem with excluding non-model fields that you explicitly declare, e.g. in a parent form class. Adding the following in your form's init will take care of it even for non-model fields (see https://code.djangoproject.com/ticket/8620).

def __init__(self, *args, **kwargs):
    super(MyForm, self).__init__(*args, **kwargs)
    [self.fields.pop(f) for f in self.fields.keys() if f in self.Meta.exclude]



回答3:


I know this is old but posting here as a reference.

I encountered this same issue because I overloaded clean_fields() on the model, but didn't call the superclass correctly.

 class MyModel(models.Model):
    foo = models.BooleanField()    

    # Wrong!  Don't do this!
    def clean_fields(self, exclude=None):
        # Bah!  Forgetting to pass exclude defaults it to None!
        super(MyModel, self).clean_fields()
        if not self.foo:
            raise ValidationError('Ah fooey.')

    # Correct!  Do it this way!
    def clean_fields(self, exclude=None):
        # That's better!  Let's take a coffee break.  I'm tired.
        super(MyModel, self).clean_fields(exclude)
        if not self.foo:
            raise ValidationError('Ah fooey.')


来源:https://stackoverflow.com/questions/8139261/why-does-my-excluded-field-still-appear-in-this-django-form

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