I want to automatically add some items to a model’s ManyToMany field when it is saved in the Django admin UI. However, calling model.many2manyfield.add() is failing silently
my django app’s models.py
...
class Dashboard(models.Model):
name = models.TextField()
url = models.TextField()
graphs = models.ManyToManyField(Graph, null=True, blank=True)
my django app’s admin.py
from models import Dashboard
...
class DashboardAdmin(GraphAdmin):
def save_model(self, request, dashboard, form, change):
dashboard.save()
graphite_util.sync_dashboard_graphs(dashboard)
...
admin.site.register(Dashboard, DashboardAdmin)
from graphite_util.py:
def sync_dashboard_graphs(dashboard):
print "Syncing %s " % dashboard
...
graph = None
try:
graph = Graph.objects.get(url=url)
except Graph.DoesNotExist:
graph = Graph()
graph.url = url
graph.save()
print "adding graph %s to dashboard %s" %(graph, dashboard)
dashboard.graphs.add(graph) #TODO: why does this fail silently?
Is what I want to do somehow illegal? If so, are there other options?
Thanks!
In principle it should work; however, you’ve got some inconsistencies in your code. For example, you’re looking up the graph based on
url. You’ve redacted part of your code, so it’s possible you created the variable in the missing part, but I’m not sure where you would have gotten that info from; you have no access to therequestfrom this method.However, you could pass the request in to the method from where it’s called in
save_modelbecause the request is available there.Additionally, if you’re simply going to create a graph in the except block, you’re better off using
get_or_create.It basically does the same thing, but much more concisely.