Skip to content

Commit

Permalink
Fix makemigrations warning for user model case
Browse files Browse the repository at this point in the history
Fix issue where a warning is raised when running makemigrations
when user model is passed with different case to the default.
This commonly happens when the default is `auth.User` and
`auth.user` is passed in the `to` field.

The fix is to detect the case difference, and update the incoming
args to match the default.

Relates to zsoldosp#43.
  • Loading branch information
jongracecox authored and Jon Grace-Cox committed Jan 11, 2022
1 parent b32c42a commit 2d9ad14
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
8 changes: 8 additions & 0 deletions django_currentuser/db/models/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,14 @@ class CurrentUserField(models.ForeignKey):

def __init__(self, *args, **kwargs):
self.on_update = kwargs.pop("on_update", False)

# If `to` is present in kwargs, and the same when ignoring case then
# update `to` to use the defaults.
# Fix for https://github.com/PaesslerAG/django-currentuser/issues/43
if "to" in kwargs \
and kwargs["to"].lower() == self.defaults['to'].lower():
kwargs["to"] = self.defaults['to']

self._warn_for_shadowing_args(*args, **kwargs)

if "on_delete" not in kwargs:
Expand Down
10 changes: 10 additions & 0 deletions tests/testapp/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,16 @@ def test_raises_warning_when_non_default_arguments_are_passed(self):
assert_that([str(m.message) for m in my_warnings],
is_([CurrentUserField.warning] * 4))

def test_no_warning_raised_when_upper_case_user_model_passed(self):
with warnings.catch_warnings(record=True) as my_warnings:
self.field_cls(to='auth.User')
assert_that(my_warnings, has_length(0))

def test_no_warning_raised_when_lower_case_user_model_passed(self):
with warnings.catch_warnings(record=True) as my_warnings:
self.field_cls(to='auth.user')
assert_that(my_warnings, has_length(0))

def test_no_warning_raised_if_passed_argument_values_match_defaults(self):
with warnings.catch_warnings(record=True) as my_warnings:
self.field_cls(default=get_current_authenticated_user)
Expand Down

0 comments on commit 2d9ad14

Please sign in to comment.