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
- [Django]-How to host Angular 6 application in Python Django?
- [Django]-Custom model method in Django
- [Django]-Django How to paginate a list of dicts
Source:stackexchange.com