简体   繁体   中英

Set default value or instance for django ModelForm ManyToMany field

I have two models inn my django application where I have ManyToMany field in one model to other. I want to set the default for ManyToMany field but getting no way to do this.
My models are

Class Model1(models.Model):
    name = models.CharField(max_length=100)

class Model2(models.Model):
    model1 = models.ManyToManyField(Model1, null=True, blank=True, default=Model1.objects.first())

but using this I am getting this error

    raise AppRegistryNotReady("Models aren't loaded yet.")
    django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.

I tried it by defining an explicit variable also like

m1 = Model1.objects.first()
and assigning this m1 variable to the field as default but same error again.

Please suggest how can I assign default value to the M2Mfield in django. I want that the first object of the choices should be selected when the modelform renders on template.

Given the way Django parses model class, you cannot do it like that, because "Models aren't loaded yet" <=> default are set at "parse time"

But you could use a callable as default.

def get_first_model1():
    return Model1.objects.first()

class Model2(models.Model):
    model1 = models.ManyToManyField(Model1, null=True, blank=True, default=get_first_model1)

It's the callable that you should use not the result value, thus the lack of parenthesis.

With this modification, default callable will be called at execution time when creating a new Model2 if you do not provide model1 attribute value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM