Search code examples
djangodjango-forms

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


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)


Solution

  • 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