Index: /waeup/branches/ulif-rewrite/src/waeup/university/certificate.py
===================================================================
--- /waeup/branches/ulif-rewrite/src/waeup/university/certificate.py	(revision 4330)
+++ /waeup/branches/ulif-rewrite/src/waeup/university/certificate.py	(revision 4331)
@@ -5,5 +5,5 @@
 from zope.component.interfaces import IFactory
 from waeup.interfaces import (ICertificate, ICertificateContainer,
-                              ICertificateCourse)
+                              ICertificateCourse, ICourse, IDepartment)
 
 class Certificate(grok.Container):
@@ -77,8 +77,39 @@
 
     def __init__(self, course=None, level=100, core_or_elective=True):
-        # XXX Make sure, this reference is deleted, when the course
-        # does not exist anymore (or the referenced course will still
-        # exist here).
         self.course = course
         self.level = level
         self.core_or_elective = core_or_elective
+
+class CertificateCourseFactory(grok.GlobalUtility):
+    """A factory for certificate courses.
+    """
+    grok.implements(IFactory)
+    grok.name(u'waeup.CertificateCourse')
+    title = u"Create a new certificate course.",
+    description = u"This factory instantiates new certificate courses."
+
+    def __call__(self):
+        return CertificateCourse()
+
+    def getInterfaces(self):
+        return implementedBy(CertificateCourse)
+
+@grok.subscribe(ICourse, grok.IObjectRemovedEvent)
+def removedCourseHandler(course, event):
+    """If a course is deleted, we make sure that also references in a
+       certificatecontainer are removed.
+    """
+    old_parent = event.oldParent
+    code = course.code
+    # Try to find a nearby certificate container...
+    dept = getattr(old_parent, '__parent__', None)
+    if not IDepartment.providedBy(dept):
+        # Hm, looks like this course was not part of a department...
+        return
+    certcontainer = dept.certificates
+    for cert in certcontainer.values():
+        # Loop through all certificatecourses in this certificate...
+        if code in cert.keys():
+            del cert[code]
+            cert._p_changed = True
+
