### Install Project Dependencies Source: https://github.com/browniebroke/django-codemod/blob/main/docs/contributing.md Install all necessary project dependencies using uv. This command ensures your local environment is set up correctly for development. ```shell $ uv sync ``` -------------------------------- ### Install Django Codemod Source: https://context7.com/browniebroke/django-codemod/llms.txt Install Django Codemod using pipx for an isolated environment, or alternatively with pip or poetry. ```bash pipx install django-codemod ``` ```bash pip install django-codemod ``` ```bash poetry add --dev django-codemod ``` -------------------------------- ### Install Prek Git Hooks Source: https://github.com/browniebroke/django-codemod/blob/main/docs/contributing.md Install prek hooks to automatically run linters and checks on each commit. This ensures code quality is maintained consistently. ```shell $ prek install -f ``` -------------------------------- ### Install and Run Django Codemod Manually Source: https://context7.com/browniebroke/django-codemod/llms.txt Install pre-commit hooks and run the djcodemod command manually on all files in your project. This is useful for one-time migrations. ```bash # Install the pre-commit hooks pre-commit install ``` ```bash # Run manually on all files pre-commit run djcodemod --all-files ``` -------------------------------- ### URL Pattern Transformation Example Source: https://context7.com/browniebroke/django-codemod/llms.txt Demonstrates the transformation of Django URL patterns from `url()` to `path()` or `re_path()` using the URLTransformer. Complex regex patterns are automatically converted to `re_path()`. ```python # Before: myapp/urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^articles/$', views.article_list), url(r'^articles/(?P[0-9]+)/$', views.article_detail), url(r'^articles/(?P[-\\w]+)/$', views.article_by_slug), url(r'^search/(?P.+)/$', views.search), url(r'^api/v[0-9]+/.*$', views.api_catch_all), # Complex regex ] ``` ```python # After running: djcodemod run --removed-in 4.0 myapp/urls.py from django.urls import path, re_path from . import views urlpatterns = [ path('articles/', views.article_list), path('articles//', views.article_detail), path('articles//', views.article_by_slug), path('search//', views.search), re_path(r'^api/v[0-9]+/.*$', views.api_catch_all), # Falls back to re_path ] ``` -------------------------------- ### Run a Subset of Tests Source: https://github.com/browniebroke/django-codemod/blob/main/docs/contributing.md Execute a specific subset of tests, for example, tests located within the 'tests' directory. This is useful for faster feedback during development. ```shell $ pytest tests ``` -------------------------------- ### Install Django Codemod with pipx Source: https://github.com/browniebroke/django-codemod/blob/main/docs/installation.md Use pipx to install the latest stable release of Django Codemod in an isolated virtual environment. This method prevents conflicts with global Python packages. ```shell pipx install django-codemod ``` -------------------------------- ### Run Codemods by Deprecated Version Source: https://context7.com/browniebroke/django-codemod/llms.txt Apply codemods for deprecations that started in a specific Django version to proactively fix warnings. This helps catch issues before they become removed features. ```bash # Fix all deprecations that started in Django 3.0 djcodemod run --deprecated-in 3.0 . ``` ```bash # Fix deprecations from multiple versions djcodemod run --deprecated-in 3.0 --deprecated-in 3.1 myapp/ ``` ```bash # Combine deprecated-in and removed-in options djcodemod run --deprecated-in 3.0 --removed-in 2.2 myproject/ settings.py ``` -------------------------------- ### Clone the Repository Source: https://github.com/browniebroke/django-codemod/blob/main/docs/contributing.md Clone your forked repository locally to begin development. Ensure you replace 'your_name_here' with your GitHub username. ```shell $ git clone git@github.com:your_name_here/django-codemod.git ``` -------------------------------- ### Mix and Match Workflows Source: https://github.com/browniebroke/django-codemod/blob/main/docs/usage.md Combine `--deprecated-in` and `--removed-in` options to address multiple version changes simultaneously. Multiple source paths can also be specified. ```bash djcodemod run --deprecated-in 3.0 --deprecated-in 3.1 --removed-in 2.2 example example1 example2/models.py settings.py ``` -------------------------------- ### List Available Codemodders Source: https://github.com/browniebroke/django-codemod/blob/main/docs/usage.md View a list of all available codemodders, their deprecated and removed versions, and descriptions. This command helps in understanding the tool's capabilities. ```bash > djcodemod list ┏━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ Codemodder ┃ Deprecated in ┃ Removed in ┃ Description ┃ ┡━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩ │ OnDeleteTransformer │ 1.9 │ 2.0 │ Add the on_delete=CASCADE to ForeignKey and OneToOneField. │ │ ... │ ... │ ... │ │ └─────────────────────┴───────────────┴────────────┴────────────────────────────────────────────────────────────┘ ``` -------------------------------- ### Create a Pull Request Source: https://github.com/browniebroke/django-codemod/blob/main/docs/contributing.md Create a pull request on GitHub to merge your changes into the main project. The --fill flag attempts to pre-populate the PR details from your commit. ```shell $ gh pr create --fill ``` -------------------------------- ### Commit and Push Changes Source: https://github.com/browniebroke/django-codemod/blob/main/docs/contributing.md Stage all changes, commit them with a descriptive message following conventional commits, and push the branch to your GitHub fork. The commit message format is validated by commitlint. ```shell $ git add . $ git commit -m "feat(something): your detailed description of your changes" $ git push origin name-of-your-bugfix-or-feature ``` -------------------------------- ### Run Tests with Pytest Source: https://github.com/browniebroke/django-codemod/blob/main/docs/contributing.md Execute the project's test suite using pytest to ensure your changes do not introduce regressions. This is a crucial step before committing. ```shell $ uv run pytest ``` -------------------------------- ### Run All Prek Linters Source: https://github.com/browniebroke/django-codemod/blob/main/docs/contributing.md Execute all linters defined in prek to check code quality and style. This command runs all checks as a one-off operation. ```shell $ prek run -a ``` -------------------------------- ### List Available Codemodders Source: https://context7.com/browniebroke/django-codemod/llms.txt Display all available codemodders in a formatted table, including their deprecation and removal versions. This helps in identifying which codemods are relevant for your Django version. ```bash # List all available codemodders in a formatted table djcodemod list ``` ```bash # Output: # ┏━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ # ┃ Codemodder ┃ Deprecated in ┃ Removed in ┃ Description ┃ # ┡━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩ # │ OnDeleteTransformer │ 1.9 │ 2.0 │ Add on_delete=CASCADE to ForeignKey │ # │ URLTransformer │ 3.0 │ 4.0 │ Update django.conf.urls.url to path │ # │ ForceTextTransformer │ 3.0 │ 4.0 │ Replace force_text by force_str │ # │ UGetTextTransformer │ 3.0 │ 4.0 │ Replace ugettext by gettext │ # │ ... │ ... │ ... │ ... │ # └─────────────────────────┴───────────────┴────────────┴───────────────────────────────────────┘ ``` -------------------------------- ### Create a New Branch Source: https://github.com/browniebroke/django-codemod/blob/main/docs/contributing.md Create a new branch for your bug fix or feature development. This helps in organizing your changes and keeping them separate from the main branch. ```shell $ git checkout -b name-of-your-bugfix-or-feature ``` -------------------------------- ### Run Specific Codemodder Source: https://context7.com/browniebroke/django-codemod/llms.txt Execute a single codemodder by name for targeted transformations. This is useful when you only need to apply one specific fix. ```bash # Run only the URL transformer on urls.py files djcodemod run --codemod URLTransformer urls.py myapp/urls.py ``` ```bash # Run specific codemod on entire project djcodemod run --codemod ForceTextTransformer . ``` ```bash # Run multiple specific codemods djcodemod run --codemod UGetTextTransformer --codemod UGetTextLazyTransformer myapp/ ``` ```bash # Combine with version options djcodemod run --codemod OnDeleteTransformer --deprecated-in 3.0 models.py ``` -------------------------------- ### Run Deprecated In Workflow Source: https://github.com/browniebroke/django-codemod/blob/main/docs/usage.md Use this command to modify code that is deprecated in a specific Django version. Run from the root of your repository. ```bash djcodemod run --deprecated-in 3.0 {source_file_or_directory} ``` -------------------------------- ### Replace force_text and smart_text with str equivalents Source: https://context7.com/browniebroke/django-codemod/llms.txt Replaces deprecated `force_text` and `smart_text` functions with their modern `force_str` and `smart_str` equivalents. This transformation is typically required for Django versions 4.0 and above. ```python # Before: myapp/utils.py from django.utils.encoding import force_text, smart_text def process_input(data): text = force_text(data) smart_data = smart_text(data, encoding='utf-8') return text, smart_data ``` ```python # After running: djcodemod run --removed-in 4.0 myapp/utils.py from django.utils.encoding import force_str, smart_str def process_input(data): text = force_str(data) smart_data = smart_str(data, encoding='utf-8') return text, smart_data ``` -------------------------------- ### Run Specific Codemodder Source: https://github.com/browniebroke/django-codemod/blob/main/docs/usage.md Execute only a particular codemodder using the `--codemod` option. This option can be repeated to run multiple specific codemodders. ```bash djcodemod run --codemod URLTransformer urls.py ``` -------------------------------- ### Configure Pre-commit Hook for Django Codemod Source: https://github.com/browniebroke/django-codemod/blob/main/docs/pre-commit-hook.md Add this configuration to your .pre-commit-config.yaml file to integrate django-codemod. Ensure the 'rev' is a version greater than 1.2.0 and adjust 'args' as needed for your specific migration requirements. ```yaml - repo: https://github.com/browniebroke/django-codemod # Any tag/version (>1.2.0): # https://github.com/browniebroke/django-codemod/tags rev: v1.2.0 hooks: - id: djcodemod # Update arguments that suits you args: ["run", "--deprecated-in", "3.0"] ``` -------------------------------- ### Pre-commit Configuration for Django Codemod Source: https://context7.com/browniebroke/django-codemod/llms.txt Configure pre-commit hooks to automatically run django-codemod. Use `--deprecated-in` to catch new deprecations or `--removed-in` for all deprecations up to a specific version. You can also specify individual codemods. ```yaml repos: - repo: https://github.com/browniebroke/django-codemod rev: v2.4.5 # Use the latest version hooks: - id: djcodemod args: ["run", "--deprecated-in", "3.0"] ``` ```yaml repos: - repo: https://github.com/browniebroke/django-codemod rev: v2.4.5 hooks: - id: djcodemod args: ["run", "--removed-in", "4.0"] ``` ```yaml repos: - repo: https://github.com/browniebroke/django-codemod rev: v2.4.5 hooks: - id: djcodemod args: ["run", "--codemod", "URLTransformer", "--codemod", "ForceTextTransformer"] ``` -------------------------------- ### Update deprecated HTTP utility functions Source: https://context7.com/browniebroke/django-codemod/llms.txt Replaces deprecated URL quoting functions (`urlquote`, `urlquote_plus`, `urlunquote`) and `is_safe_url` with their standard library equivalents (`quote`, `quote_plus`) and `url_has_allowed_host_and_scheme`. This is required for Django versions 4.0 and above. ```python # Before: myapp/utils.py from django.utils.http import urlquote, urlquote_plus, urlunquote, is_safe_url def build_url(path, query): safe_path = urlquote(path) safe_query = urlquote_plus(query) return f"{safe_path}?q={safe_query}" def validate_redirect(url, host): return is_safe_url(url, allowed_hosts={host}) ``` ```python # After running: djcodemod run --removed-in 4.0 myapp/utils.py from urllib.parse import quote, quote_plus from django.utils.http import url_has_allowed_host_and_scheme def build_url(path, query): safe_path = quote(path) safe_query = quote_plus(query) return f"{safe_path}?q={safe_query}" def validate_redirect(url, host): return url_has_allowed_host_and_scheme(url, allowed_hosts={host}) ``` -------------------------------- ### Run Removed In Workflow Source: https://github.com/browniebroke/django-codemod/blob/main/docs/usage.md Use this command to fix code that has been removed in a specific Django version. This is useful when upgrading to a new version. ```bash djcodemod run --removed-in 4.0 {source_file_or_directory} ``` -------------------------------- ### Update deprecated ugettext functions Source: https://context7.com/browniebroke/django-codemod/llms.txt Replaces deprecated `ugettext`, `ugettext_lazy`, and `ungettext` functions with their modern equivalents `gettext`, `gettext_lazy`, and `ngettext`. This ensures compatibility with newer Django versions. ```python # Before: myapp/views.py from django.utils.translation import ugettext, ugettext_lazy, ungettext class MyView: title = ugettext_lazy("Page Title") def get_message(self, count): return ungettext( "%(count)d item", "%(count)d items", count ) % {'count': count} def greet(self): return ugettext("Hello, World!") ``` ```python # After running: djcodemod run --removed-in 4.0 myapp/views.py from django.utils.translation import gettext, gettext_lazy, ngettext class MyView: title = gettext_lazy("Page Title") def get_message(self, count): return ngettext( "%(count)d item", "%(count)d items", count ) % {'count': count} def greet(self): return gettext("Hello, World!") ``` -------------------------------- ### Programmatic Usage of Django Codemod Transformers Source: https://context7.com/browniebroke/django-codemod/llms.txt Use django-codemod transformers programmatically in custom Python scripts. Define transformers, create a command, and process files using `parallel_exec_transform_with_prettyprint`. ```python from pathlib import Path from libcst.codemod import CodemodContext from django_codemod.commands import BaseCodemodCommand from django_codemod.visitors import \ URLTransformer, ForceTextTransformer, UGetTextTransformer # Define which transformers to run transformers = [ URLTransformer, ForceTextTransformer, UGetTextTransformer, ] # Create the command with transformers context = CodemodContext() command = BaseCodemodCommand(transformers, context) # Process files from libcst.codemod import parallel_exec_transform_with_prettyprint files = [Path("myapp/urls.py"), Path("myapp/views.py")] result = parallel_exec_transform_with_prettyprint(command, files) print(f"Transformed: {result.successes}") print(f"Skipped: {result.skips}") print(f"Failed: {result.failures}") ``` -------------------------------- ### Run Codemods by Removed Version Source: https://context7.com/browniebroke/django-codemod/llms.txt Apply all codemods for deprecations that were removed in a specific Django version. This command targets fixes for versions where features are no longer supported. ```bash # Fix all deprecations removed in Django 4.0 djcodemod run --removed-in 4.0 . ``` ```bash # Fix deprecations removed in Django 3.0 on specific directory djcodemod run --removed-in 3.0 myapp/ ``` ```bash # Fix deprecations removed in multiple versions djcodemod run --removed-in 3.0 --removed-in 4.0 myproject/ ``` ```bash # Example output: # Running codemods: ForceTextTransformer, SmartTextTransformer, URLTransformer, ... # Finished codemodding 150 files! # - Transformed 23 files successfully. # - Skipped 127 files. # - Failed to codemod 0 files. # - 0 warnings were generated. ``` -------------------------------- ### Add on_delete to ForeignKey and OneToOneField Source: https://context7.com/browniebroke/django-codemod/llms.txt Adds the required `on_delete` argument to `ForeignKey` and `OneToOneField` models. Ensure to specify the appropriate deletion behavior (e.g., `models.CASCADE`). ```python # Before: myapp/models.py from django.db import models class Article(models.Model): author = models.ForeignKey('auth.User') category = models.ForeignKey('Category', null=True, blank=True) parent = models.OneToOneField('self') ``` ```python # After running: djcodemod run --removed-in 2.0 myapp/models.py from django.db import models class Article(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.CASCADE) parent = models.OneToOneField('self', on_delete=models.CASCADE) ``` -------------------------------- ### Replace @models.permalink decorator with reverse() Source: https://context7.com/browniebroke/django-codemod/llms.txt Replaces the deprecated `@models.permalink` decorator with `reverse()` calls. This transformation is necessary for Django versions 2.1 and above, promoting the use of the standard URL reversing mechanism. ```python # Before: myapp/models.py from django.db import models class Article(models.Model): slug = models.SlugField() @models.permalink def get_absolute_url(self): return ('article_detail', (), {'slug': self.slug}) ``` ```python # After running: djcodemod run --removed-in 2.1 myapp/models.py from django.db import models from django.urls import reverse class Article(models.Model): slug = models.SlugField() def get_absolute_url(self): return reverse('article_detail', None, (), {'slug': self.slug}) ``` -------------------------------- ### Replace NullBooleanField with BooleanField(null=True) Source: https://context7.com/browniebroke/django-codemod/llms.txt Replaces the deprecated `NullBooleanField` with `BooleanField(null=True)`. This change is necessary for Django versions 4.0 and above. Note that `default=None` is preserved. ```python # Before: myapp/models.py from django.db import models class Survey(models.Model): is_active = models.NullBooleanField() has_consent = models.NullBooleanField(default=None, help_text="User consent") ``` ```python # After running: djcodemod run --removed-in 4.0 myapp/models.py from django.db import models class Survey(models.Model): is_active = models.BooleanField(null=True) has_consent = models.BooleanField(default=None, help_text="User consent", null=True) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.