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)
Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.
Every field comes in with built-in validations from Django validators. One can also add more built-in field validations for applying or removing certain constraints on a particular field. editable=False will make the field disappear from all forms including admin and ModelForm i.e., it can not be edited using any form.
The simplest way is by using the field option blank=True (docs.djangoproject.com/en/dev/ref/models/fields/#blank).
Django Model Form It is a class which is used to create an HTML form by using the Model. It is an efficient way to create a form without writing HTML code. Django automatically does it for us to reduce the application development time.
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
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With