Opened 7 years ago

Closed 7 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']


Change History (1)

comment:1 by Simon Charette, 7 years ago

Resolution: invalid
Status: newclosed

Hello there,

That's expected as your ModelForm subclass will create a ModelB instance on initialization as you didn't provide one yourself.

You should pass an instance=ModelB(reference=None) when creating a MyForm instance yourself and then make sure to assign a ModelA instance to form.instance.reference before 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.

Note: See TracTickets for help on using tickets.
Back to Top