[Django]-How to set default values for manytomanyfield

3πŸ‘

βœ…

For the Form what is working for me in 1.3.1:

is something similar to this, the manytomany in the inital

with hardcode ids:

def MyView(request):
    if request.method == 'GET':
        model   = MyModel( name = "my default name")
        initial = { 'relatedModels': [1,] } # assuming you knew the id and wanted to hardcode it
        form = MyForm( instance=model, initial=initial )
        return render_to_response("my_template.html", {"form" : form}, context_instance=RequestContext(request))

using a query to populate by names:

def MyView(request):
    if request.method == 'GET':
        model   = MyModel( name = "my default name")
        initial = { 'relatedModels':  [ o.pk for o in list(MyRelatedModel.objects.filter( name__in=("related model 1", "related model 2", "related model 3")))], } 
        form = MyForm( instance=model, initial=initial )
        return render_to_response("my_template.html", {"form" : form}, context_instance=RequestContext(request))
πŸ‘€sfossen

1πŸ‘

for name in ["related model 1", "related model 2", "related model 3"]:
    relatedModel = MyRelatedModel(name=name)
    relatedModel.save()
    self.relatedModels.add(relatedModel)

Or:

newRelatedModels = []
for name in ["related model 1", "related model 2", "related model 3"]:
    relatedModel = MyRelatedModel(name=name)
    relatedModel.save()
    newRelatedModels.append(relatedModel)
self.relatedModels.add(*newRelatedModels)

This should work too:

self.relatedModels = newRelatedModels
πŸ‘€San4ez

Leave a comment