<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def redirect_territory(level, code):
 """ Implicit redirect given the INSEE code. Optimistically redirect to the latest valid/known INSEE code. """

    territory = GeoZone.objects.valid_at(datetime.now()).filter(
        code=code, level='fr:{level}'.format(level=level)).first()
    return redirect(url_for('territories.territory', territory=territory))