Opened 8 years ago
Closed 8 years ago
#28494 closed Bug (invalid)
ModelForms calls default on fields that ain't selected.
| Reported by: | skruven96 | Owned by: | nobody |
|---|---|---|---|
| Component: | Forms | Version: | 1.11 |
| Severity: | Normal | Keywords: | ModelForm field default |
| Cc: | Triage Stage: | Unreviewed | |
| Has patch: | no | Needs documentation: | no |
| Needs tests: | no | Patch needs improvement: | no |
| Easy pickings: | no | UI/UX: | no |
Description
Hello,
Every time you create an instance of MyForm in the example below create_a function gets called which creates an instance of ModelA which clutters the database with ModelAs.
# models.py
def create_a():
return ModelA.objects.create(name='<default-name>').id
class ModelA(models.Model):
pass
class ModelB(models.Model):
name = models.CharField(max_length=123)
reference = models.ForeignKey(ModelA, default=create_a)
# views.py
class MyForm(ModelForm):
class Meta:
model = ModelB
fields = ['name']
Note:
See TracTickets
for help on using tickets.
Hello there,
That's expected as your
ModelFormsubclass will create aModelBinstance on initialization as you didn't provide one yourself.You should pass an
instance=ModelB(reference=None)when creating aMyForminstance yourself and then make sure to assign aModelAinstance toform.instance.referencebefore saving it.For such usage questions please use our support channels instead as this bug tracker is exclusively devoted to serve the development of Django itself.