Recent studies show that district heating infrastructures should play an important role in future sustainable energy systems. Tools for dynamic optimization are required to increase the efficiency of existing systems and design new ones. This paper presents a novel framework to represent, simplify, simulate and optimize district heating systems. The framework is implemented in Python and is based on Optimica Compiler Toolkit as well as Modelon's Thermal Power Library. The high-level description of optimization problems using Optimica allows flexible optimization formulations including constraints on physically relevant variables such as supply temperature, flow rate and pressures. The benefit of new algorithms for symbolic elimination in Optimica Compiler Toolkit is also investigated. The framework is applied on a test case, which is based on a planned city district located in Graz, Austria. The results demonstrate the generality of the representation as well as the accuracy of the simplification for dynamic optimization of temperature supply and pressure control.