Is there an “instance must have primary key value before using many-to-many” error?
I have a model with several fields, including a many-to-many relationship to another model. I have a function to set default values for these fields when I create a new instance of the model. I do this in a view when processing HTTP GET. The m2m field is displayed using a set of forms.
Here are some pseudo codes describing the situation:
class MyRelatedModel(models.Model):
name = models.CharField(max_length=100,blank=True)
class MyModel(models.Model):
name = models.CharField(max_length=100,blank=True)
relatedModels = models.ManyToManyField("MyRelatedModel")
def initialize(self):
self.name = "my default name"
newRelatedModels = []
for name in ["related model 1", "related model 2", "related model 3"]:
relatedModel = MyRelatedModel(name=name)
relatedModel.save()
newRelatedModels.append(relatedModel.id)
self.relatedModels = newRelatedModels
def MyView(request):
if request.method == 'GET':
model = MyModel()
model.initialize()
form = MyForm(instance=model)
return render_to_response("my_template.html", {"form" : form}, context_instance=RequestContext(request))
Any suggestions?
I suspect that I may need to handle this on the form side, and not on the model side, but that bothers me too.
source
share