# Fix "ImportError: cannot import name 'contextfilter' from 'jinja2'"

Yes. An agent renames the decorator to pass_context, builds your templates on the old and new Jinja2, shows the output is identical and lifts the version pin.

[Run this on Rush](https://cloud.getrush.ai/run/fix-jinja2-contextfilter-import-error/jinja2/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

Many projects never see this error because they pinned their way around it, and the pin is what the agent goes looking for. In grski/braindead, a small static site generator, `pyproject.toml` has `jinja2 = "==3.0.3"`, an exact version among dependencies that otherwise use caret ranges, and `poetry.lock` records the same release. The reason sits in `braindead/jinja_filters.py`: line 2 is `from jinja2 import contextfilter`, and line 8 decorates `jinja_i18n`, the filter behind `{{ "read-more" | i18n }}` in the default template's `index.html`. Jinja2 3.1.0 removed that name. With the pin in place every weekly upgrade run skips Jinja2, and anyone who installs the code next to a newer Jinja2 gets the import error before a single page renders.

The agent reproduces both sides. It installs the locked 3.0.3 and builds a three-file sample site with `python -m braindead build`; the build passes and, with warnings shown, prints `'contextfilter' is renamed to 'pass_context', the old name will be removed in Jinja 3.1.` pointing at line 8. It keeps that `dist` directory as the baseline. In a second environment with the newest Jinja2 the same command stops in `jinja_utils.py`, which imports the filters module, with the error in the title.

The fix is two words, and the useful part is the order it is applied in. `pass_context` already exists in 3.0.3, so the agent makes the rename first, while the pin is still there, rebuilds, and runs `diff -r` against the baseline: no difference. Only then does it loosen the pin to a caret range, refresh the lock, rebuild on the new release, and diff again: still no difference. Two small commits, each with its own proof, mean a reviewer can take the rename today and the upgrade later if they want to.

Before calling the pin safe to lift, it checks what else the same release took away. Comparing the public names of the two versions gives eight that are gone: `contextfilter`, `contextfunction`, `environmentfilter`, `environmentfunction`, `evalcontextfilter`, `evalcontextfunction`, `Markup` and `escape`. The agent searches the package and the templates for each. In the fixture only the first appears; a project that imported `Markup` or `escape` from `jinja2` would get the import moved to `markupsafe` in the same pull request. It also reads how filters are registered. `jinja_utils.py` adds every module attribute whose name starts with `jinja_`, so the new import does not register anything by accident, and the environment is created with `autoescape=False`, which the agent reports and leaves as it is.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "This project pins Jinja2 to an exact old version, and with a newer Jinja2 it fails with \"ImportError: cannot import name 'contextfilter' from 'jinja2'\". Find the pin in the dependency file and the lock file, and find every use of the names Jinja2 3.1 removed: contextfilter, contextfunction, environmentfilter, environmentfunction, evalcontextfilter, evalcontextfunction, and Markup or escape imported from jinja2. Search templates as well as Python files, and read how custom filters and globals are registered. Create a small sample input that makes every custom filter run, build it with the pinned Jinja2 with warnings shown, and keep the output directory as a baseline. Work in two commits. First, with the pin unchanged, replace the removed names with pass_context, pass_environment, pass_eval_context or the markupsafe imports, rebuild, and show a recursive diff against the baseline. Second, relax the pin to a compatible range, update the lock file with the project's own tool, rebuild on the newest Jinja2, and diff again. Reproduce the original ImportError on the newest Jinja2 before the first commit and include it. Do not change template output, autoescape settings or the filters' behaviour; if a diff is not empty, stop and report it. Read the CI and release workflows and say in the pull request what merging will trigger. Open a pull request with both diffs and the warning text from the old version.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

A pull request with two commits. The first changes two lines of `braindead/jinja_filters.py`. The second changes one line of `pyproject.toml` and regenerates `poetry.lock`. The description quotes the deprecation warning from 3.0.3 and the ImportError from the newest release, lists the eight removed names with the search result for each, and shows the two empty diffs: baseline against the renamed code on the old Jinja2, and baseline against the renamed code on the new one. The sample input used for the builds is described so anyone can repeat it.

A reviewer has two things to weigh that the diff alone does not show. One is the lock file, where a refresh can move packages other than Jinja2; the agent lists every version that changed. The other is what a merge sets off. In the fixture, `.github/workflows/deploy.yml` runs when a pull request into `master` or `develop` is closed as merged, bumps the version and publishes the package, so merging this is a release. The pull request says so in its first paragraph. If either diff is not empty, the session ends for review with the differing files named and no pull request claiming success.

## Run it on every weekly upgrade run

Exact pins are where scheduled upgrades go quiet. Put this prompt in an automation with a `schedule` trigger, for example a cron of `0 9 * * 1`, and word it for the general case: find dependencies pinned to an exact version, check whether the newest release imports and builds, and fix what the upgrade breaks. The Jinja2 pin is handled the first week; the same run reports the next exact pin it finds instead of stepping over it.

To start one on demand, a `github` trigger on `pull_request.labeled` with a label such as `unpin` works when a maintainer applies it to an upgrade pull request that failed. Pull requests opened by bots do not fire triggers themselves, so a person adding the label is the event. One run per repository is enough; keep max runs per hour at a low number.

## Why run it on Rush?

The evidence for this change is a comparison between two installed versions of one library, and that needs two clean environments built from the same lock file. On a developer's machine there is one virtualenv, it has whichever Jinja2 was installed last, and switching back and forth to produce a baseline is exactly the chore that gets skipped. A Rush run creates both environments in its sandbox, builds the same input in each, and keeps the commands and diffs in the session for the reviewer.

It also separates a safe change from a risky one. A decorator rename that works on the pinned version can be merged with no upgrade at all, and the run proves that before touching the pin. When the upgrade does land, the lock file changes are listed, the release workflow is named, and the output of the templates is shown to be byte for byte what it was.

## Frequently asked questions

### What replaced contextfilter in Jinja2?

`pass_context`. Jinja2 3.0 added `pass_context`, `pass_environment` and `pass_eval_context` as single decorators for filters, functions and tests, and 3.1 removed the six older names. The decorated function keeps its signature, with the context as the first argument.

### Can I make the code work on both Jinja2 3.0 and 3.1?

Yes, with no compatibility shim. `pass_context` exists in 3.0.3, where the old name only warns, so the renamed code runs on both. The agent verifies this by building on each and diffing the output. Support for Jinja2 2.x would need a try and except around the import.

### The error comes from a library I installed, not my code. What then?

Then the fix is a version of that library that supports Jinja2 3.1, or a pin on Jinja2 until one exists. The agent reads the traceback to see which package owns the import, checks that package's newer releases in a clean environment, and proposes the upgrade or the pin with the reason.

### Will my rendered pages change?

They should not, and the run checks. It builds a sample that exercises every custom filter before and after, and compares the directories recursively. A non-empty diff stops the work and is reported instead of being merged around.

### Does lifting the pin upgrade other packages?

Refreshing a lock file can. The pull request lists each package whose locked version moved, so the change under review is visible and not buried in a regenerated file.

## More Jinja2 jobs

- [Fix "ImportError: cannot import name 'escape' from 'jinja2'" in a Flask 1.x App](https://getrush.ai/run/fix-jinja2-escape-import-error/jinja2/)

## More jobs like this: Upgrade dependencies weekly

- [Fix "line" is not a registered controller When Upgrading Chart.js](https://getrush.ai/run/fix-line-is-not-a-registered-controller/chart-js/)
- [Fix "ImportError: load_boston has been removed from scikit-learn since version 1.2"](https://getrush.ai/run/fix-load-boston-import-error/scikit-learn/)
- [Fix "IllegalAccessError: class lombok.javac.apt.LombokProcessor cannot access class com.sun.tools.javac.processing.JavacProcessingEnvironment"](https://getrush.ai/run/fix-lombok-illegalaccesserror/lombok/)
- [Fix --compilers Is DEPRECATED and No Longer Supported After a Mocha Upgrade](https://getrush.ai/run/fix-mocha-compilers-is-deprecated-and-no-longer-supported/mocha/)
- [Fix "Module 'networkx' Has No Attribute 'from_numpy_matrix'" After a NetworkX 3 Upgrade](https://getrush.ai/run/fix-networkx-from-numpy-matrix-attribute-error/networkx/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
