Replace references to Django core `User` model with `get_user_model`

This commit is contained in:
Christopher C. Wells 2023-02-06 06:59:57 -08:00 committed by Christopher Charbonneau Wells
parent c1f788bb49
commit cd44a473cf
19 changed files with 72 additions and 73 deletions

View File

@ -3,7 +3,7 @@ from copy import deepcopy
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from django.contrib.auth.models import User
from django.contrib.auth import get_user_model
from django.utils import timezone
from taggit.serializers import TagListSerializerField, TaggitSerializer
@ -227,7 +227,7 @@ class TimerSerializer(CoreModelSerializer):
required=False,
)
user = serializers.PrimaryKeyRelatedField(
allow_null=True, allow_empty=True, queryset=User.objects.all(), required=False
allow_null=True, allow_empty=True, queryset=get_user_model().objects.all(), required=False
)
class Meta:
@ -267,7 +267,7 @@ class WeightSerializer(CoreModelSerializer, TaggableSerializer):
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
model = get_user_model()
fields = (
"id",
"username",

View File

@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
from babybuddy.models import User
from babybuddy.models import get_user_model
from core import models
from django.urls import reverse
from django.utils import timezone
@ -35,7 +35,7 @@ class TestBase:
def test_post_with_timer(self):
if not self.timer_test_data:
return
user = User.objects.first()
user = get_user_model().objects.first()
start = timezone.now() - timezone.timedelta(minutes=10)
timer = models.Timer.objects.create(user=user, start=start)
self.timer_test_data["timer"] = timer.id
@ -64,7 +64,7 @@ class TestBase:
def test_post_with_timer_with_child(self):
if not self.timer_test_data:
return
user = User.objects.first()
user = get_user_model().objects.first()
child = models.Child.objects.first()
start = timezone.now() - timezone.timedelta(minutes=10)
timer = models.Timer.objects.create(user=user, child=child, start=start)
@ -725,7 +725,7 @@ class TimerAPITestCase(TestBase.BabyBuddyAPITestCaseBase):
self.assertEqual(obj.name, data["name"])
def test_post_default_user(self):
user = User.objects.first()
user = get_user_model().objects.first()
response = self.client.post(self.endpoint)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
obj = models.Timer.objects.get(pk=response.data["id"])

View File

@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.models import User
from django.contrib.auth import get_user_model
from django.utils.translation import gettext_lazy as _
from babybuddy import models
@ -30,5 +30,5 @@ class UserAdmin(BaseUserAdmin):
inlines = (SettingsInline,)
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
admin.site.unregister(get_user_model())
admin.site.register(get_user_model(), UserAdmin)

View File

@ -1,14 +1,14 @@
# -*- coding: utf-8 -*-
from django import forms
from django.contrib.auth.forms import PasswordChangeForm, UserCreationForm
from django.contrib.auth.models import User
from django.contrib.auth import get_user_model
from .models import Settings
class UserAddForm(UserCreationForm):
class Meta:
model = User
model = get_user_model()
fields = [
"username",
"first_name",
@ -29,7 +29,7 @@ class UserAddForm(UserCreationForm):
class UserUpdateForm(forms.ModelForm):
class Meta:
model = User
model = get_user_model()
fields = [
"username",
"first_name",
@ -42,7 +42,7 @@ class UserUpdateForm(forms.ModelForm):
class UserForm(forms.ModelForm):
class Meta:
model = User
model = get_user_model()
fields = ["first_name", "last_name", "email"]

View File

@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
from django.contrib.auth.models import User
from django.contrib.auth import get_user_model
from django.core.management.commands import migrate
@ -9,9 +9,9 @@ class Command(migrate.Command):
def handle(self, *args, **kwargs):
super(Command, self).handle(*args, **kwargs)
superusers = User.objects.filter(is_superuser=True)
superusers = get_user_model().objects.filter(is_superuser=True)
if len(superusers) == 0:
default_user = User.objects.create_user("admin", password="admin")
default_user = get_user_model().objects.create_user("admin", password="admin")
default_user.is_superuser = True
default_user.is_staff = True
default_user.save()

View File

@ -1,14 +1,15 @@
# -*- coding: utf-8 -*-
from django.conf import settings
from django.db import migrations
def add_settings(apps, schema_editor):
Settings = apps.get_model("babybuddy", "Settings")
User = apps.get_model("auth", "User")
User = apps.get_model(settings.AUTH_USER_MODEL)
for user in User.objects.all():
if Settings.objects.filter(user=user).count() == 0:
settings = Settings.objects.create(user=user)
settings.save()
user_settings = Settings.objects.create(user=user)
user_settings.save()
class Migration(migrations.Migration):

View File

@ -2,7 +2,7 @@
import pytz
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.auth import get_user_model
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
@ -14,7 +14,7 @@ from rest_framework.authtoken.models import Token
class Settings(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
dashboard_refresh_rate = models.DurationField(
verbose_name=_("Refresh rate"),
help_text=_(
@ -94,12 +94,12 @@ class Settings(models.Model):
return None
@receiver(post_save, sender=User)
@receiver(post_save, sender=get_user_model())
def create_user_settings(sender, instance, created, **kwargs):
if created:
Settings.objects.create(user=instance)
@receiver(post_save, sender=User)
@receiver(post_save, sender=get_user_model())
def save_user_settings(sender, instance, **kwargs):
instance.settings.save()

View File

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
from django.test import TransactionTestCase
from django.contrib.auth.models import User, Group
from django.contrib.auth import get_user_model
from django.core.management import call_command
from core.models import Child
@ -9,7 +9,7 @@ from core.models import Child
class CommandsTestCase(TransactionTestCase):
def test_migrate(self):
call_command("migrate", verbosity=0)
self.assertIsInstance(User.objects.get(username="admin"), User)
self.assertIsInstance(get_user_model().objects.get(username="admin"), get_user_model())
def test_fake(self):
call_command("migrate", verbosity=0)
@ -20,7 +20,7 @@ class CommandsTestCase(TransactionTestCase):
def test_reset(self):
call_command("reset", verbosity=0, interactive=False)
self.assertIsInstance(User.objects.get(username="admin"), User)
self.assertIsInstance(get_user_model().objects.get(username="admin"), get_user_model())
self.assertEqual(Child.objects.count(), 1)
def test_createuser(self):
@ -31,9 +31,9 @@ class CommandsTestCase(TransactionTestCase):
password="test",
verbosity=0,
)
self.assertIsInstance(User.objects.get(username="test"), User)
self.assertIsInstance(get_user_model().objects.get(username="test"), get_user_model())
self.assertFalse(
User.objects.filter(username="test", is_staff=True, is_superuser=True)
get_user_model().objects.filter(username="test", is_staff=True, is_superuser=True)
)
call_command(
"createuser",
@ -43,7 +43,7 @@ class CommandsTestCase(TransactionTestCase):
password="test",
verbosity=0,
)
self.assertIsInstance(User.objects.get(username="testadmin"), User)
self.assertIsInstance(get_user_model().objects.get(username="testadmin"), get_user_model())
self.assertTrue(
User.objects.filter(username="testadmin", is_staff=True, is_superuser=True)
get_user_model().objects.filter(username="testadmin", is_staff=True, is_superuser=True)
)

View File

@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
import datetime
from django.contrib.auth.models import User
from django.contrib.auth import get_user_model
from django.core.management import call_command
from django.test import Client as HttpClient, override_settings, TestCase
from django.utils import timezone
@ -24,7 +24,7 @@ class FormsTestCase(TestCase):
"username": fake_user["username"],
"password": fake.password(),
}
cls.user = User.objects.create_user(is_superuser=True, **cls.credentials)
cls.user = get_user_model().objects.create_user(is_superuser=True, **cls.credentials)
cls.settings_template = {
"first_name": "User",
@ -84,8 +84,8 @@ class FormsTestCase(TestCase):
page = self.c.post("/users/add/", params)
self.assertEqual(page.status_code, 302)
new_user = User.objects.get(username="username")
self.assertIsInstance(new_user, User)
new_user = get_user_model().objects.get(username="username")
self.assertIsInstance(new_user, get_user_model())
params["first_name"] = "Changed"
page = self.c.post("/users/{}/edit/".format(new_user.id), params)
@ -95,7 +95,7 @@ class FormsTestCase(TestCase):
page = self.c.post("/users/{}/delete/".format(new_user.id))
self.assertEqual(page.status_code, 302)
self.assertQuerysetEqual(User.objects.filter(username="username"), [])
self.assertQuerysetEqual(get_user_model().objects.filter(username="username"), [])
def test_user_settings(self):
self.c.login(**self.credentials)
@ -110,14 +110,14 @@ class FormsTestCase(TestCase):
def test_user_regenerate_api_key(self):
self.c.login(**self.credentials)
api_key_before = User.objects.get(pk=self.user.id).settings.api_key()
api_key_before = get_user_model().objects.get(pk=self.user.id).settings.api_key()
params = self.settings_template.copy()
params["api_key_regenerate"] = "Regenerate"
page = self.c.post("/user/settings/", params, follow=True)
self.assertEqual(page.status_code, 200)
new_api_key = User.objects.get(pk=self.user.id).settings.api_key()
new_api_key = get_user_model().objects.get(pk=self.user.id).settings.api_key()
self.assertNotEqual(api_key_before, new_api_key)
# API key can also be regenerated on the add-device page
@ -125,7 +125,7 @@ class FormsTestCase(TestCase):
params = {"api_key_regenerate": "Regenerate"}
page = self.c.post("/user/add-device/", params, follow=True)
self.assertEqual(page.status_code, 200)
new_api_key = User.objects.get(pk=self.user.id).settings.api_key()
new_api_key = get_user_model().objects.get(pk=self.user.id).settings.api_key()
self.assertNotEqual(api_key_before, new_api_key)
def test_invalid_post_to_add_device(self):

View File

@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
from django.contrib.auth.models import User
from django.contrib.auth import get_user_model
from django.core.management import call_command
from django.test import TestCase
@ -12,7 +12,7 @@ class SettingsTestCase(TestCase):
def test_settings(self):
credentials = {"username": "Test", "password": "User"}
user = User.objects.create_user(is_superuser=True, **credentials)
user = get_user_model().objects.create_user(is_superuser=True, **credentials)
self.assertIsInstance(user.settings, Settings)
self.assertEqual(user.settings.dashboard_refresh_rate_milliseconds, 60000)

View File

@ -4,7 +4,7 @@ import time
from django.test import TestCase, override_settings, tag
from django.test import Client as HttpClient
from django.contrib.auth.models import User
from django.contrib.auth import get_user_model
from django.core import mail
from django.core.management import call_command
@ -25,7 +25,7 @@ class ViewsTestCase(TestCase):
"username": fake_user["username"],
"password": fake.password(),
}
cls.user = User.objects.create_user(
cls.user = get_user_model().objects.create_user(
is_superuser=True, email="admin@admin.admin", **cls.credentials
)
@ -71,7 +71,7 @@ class ViewsTestCase(TestCase):
page = self.c.get("/users/add/")
self.assertEqual(page.status_code, 200)
entry = User.objects.first()
entry = get_user_model().objects.first()
page = self.c.get("/users/{}/edit/".format(entry.id))
self.assertEqual(page.status_code, 200)
page = self.c.get("/users/{}/delete/".format(entry.id))

View File

@ -2,7 +2,7 @@
from django.contrib import messages
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.forms import PasswordChangeForm
from django.contrib.auth.models import User
from django.contrib.auth import get_user_model
from django.contrib.auth.views import LogoutView as LogoutViewBase
from django.contrib.messages.views import SuccessMessageMixin
from django.core.exceptions import BadRequest
@ -87,7 +87,7 @@ class LogoutView(LogoutViewBase):
class UserList(StaffOnlyMixin, BabyBuddyFilterView):
model = User
model = get_user_model()
template_name = "babybuddy/user_list.html"
ordering = "username"
paginate_by = 10
@ -95,7 +95,7 @@ class UserList(StaffOnlyMixin, BabyBuddyFilterView):
class UserAdd(StaffOnlyMixin, PermissionRequiredMixin, SuccessMessageMixin, CreateView):
model = User
model = get_user_model()
template_name = "babybuddy/user_form.html"
permission_required = ("admin.add_user",)
form_class = forms.UserAddForm
@ -106,7 +106,7 @@ class UserAdd(StaffOnlyMixin, PermissionRequiredMixin, SuccessMessageMixin, Crea
class UserUpdate(
StaffOnlyMixin, PermissionRequiredMixin, SuccessMessageMixin, UpdateView
):
model = User
model = get_user_model()
template_name = "babybuddy/user_form.html"
permission_required = ("admin.change_user",)
form_class = forms.UserUpdateForm
@ -117,7 +117,7 @@ class UserUpdate(
class UserDelete(
StaffOnlyMixin, PermissionRequiredMixin, DeleteView, SuccessMessageMixin
):
model = User
model = get_user_model()
template_name = "babybuddy/user_confirm_delete.html"
permission_required = ("admin.delete_user",)
success_url = reverse_lazy("babybuddy:user-list")

View File

@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
from django.contrib.auth.models import User
from django.contrib.auth import get_user_model
from django.core.management import call_command
from django.test import TestCase
from django.test import Client as HttpClient
@ -26,7 +26,7 @@ class FormsTestCaseBase(TestCase):
fake_user = fake.simple_profile()
credentials = {"username": fake_user["username"], "password": fake.password()}
cls.user = User.objects.create_user(is_superuser=True, **credentials)
cls.user = get_user_model().objects.create_user(is_superuser=True, **credentials)
cls.c.login(**credentials)
cls.child = models.Child.objects.create(

View File

@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
from django.contrib.auth.models import User
from django.contrib.auth import get_user_model
from django.core.management import call_command
from django.test import TestCase
from django.utils import timezone
@ -268,7 +268,7 @@ class TimerTestCase(TestCase):
child = models.Child.objects.create(
first_name="First", last_name="Last", birth_date=timezone.localdate()
)
self.user = User.objects.first()
self.user = get_user_model().objects.first()
self.named = models.Timer.objects.create(
name="Named", end=timezone.localtime(), user=self.user, child=child
)
@ -317,7 +317,7 @@ class TimerTestCase(TestCase):
self.assertFalse(self.unnamed.active)
def test_timer_duration(self):
timer = models.Timer.objects.create(user=User.objects.first())
timer = models.Timer.objects.create(user=get_user_model().objects.first())
timer.start = timezone.localtime() - timezone.timedelta(minutes=30)
timer.save()
timer.refresh_from_db()

View File

@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
import unittest
from django.contrib.auth.models import User
from django.contrib.auth import get_user_model
from django.test import TestCase, override_settings
from django.utils import timezone, formats
@ -119,7 +117,7 @@ class TemplateTagsTestCase(TestCase):
child = Child.objects.create(
first_name="Test", last_name="Child", birth_date=timezone.localdate()
)
user = User.objects.create_user(username="timer")
user = get_user_model().objects.create_user(username="timer")
timer = Timer.objects.create(user=user)
url = timers.instance_add_url({"timer": timer}, "core:sleep-add")
@ -132,7 +130,7 @@ class TemplateTagsTestCase(TestCase):
)
def test_datetimepicker_format(self):
request = MockUserRequest(User.objects.first())
request = MockUserRequest(get_user_model().objects.first())
request.user.settings.dashboard_hide_empty = True
context = {"request": request}
@ -150,7 +148,7 @@ class TemplateTagsTestCase(TestCase):
@override_settings(USE_24_HOUR_TIME_FORMAT=False)
def test_datetimepicker_format_en_gb(self):
user = User.objects.first()
user = get_user_model().objects.first()
user.settings.language = "en-GB"
user.save()

View File

@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
from django.contrib.auth.models import User
from django.contrib.auth import get_user_model
from django.core.management import call_command
from django.test import TestCase
from django.test import Client as HttpClient
@ -25,7 +25,7 @@ class ViewsTestCase(TestCase):
"username": fake_user["username"],
"password": fake.password(),
}
cls.user = User.objects.create_user(is_superuser=True, **cls.credentials)
cls.user = get_user_model().objects.create_user(is_superuser=True, **cls.credentials)
cls.c.login(**cls.credentials)

View File

@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
import pytz
from django.contrib.auth.models import User
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.utils import timezone
@ -24,7 +24,7 @@ class TemplateTagsTestCase(TestCase):
def setUpClass(cls):
super(TemplateTagsTestCase, cls).setUpClass()
cls.child = models.Child.objects.first()
cls.context = {"request": MockUserRequest(User.objects.first())}
cls.context = {"request": MockUserRequest(get_user_model().objects.first())}
# Ensure timezone matches the one defined by fixtures.
user_timezone = Settings.objects.first().timezone
@ -35,14 +35,14 @@ class TemplateTagsTestCase(TestCase):
cls.date = timezone.make_aware(date)
def test_hide_empty(self):
request = MockUserRequest(User.objects.first())
request = MockUserRequest(get_user_model().objects.first())
request.user.settings.dashboard_hide_empty = True
context = {"request": request}
hide_empty = cards._hide_empty(context)
self.assertTrue(hide_empty)
def test_filter_data_age_none(self):
request = MockUserRequest(User.objects.first())
request = MockUserRequest(get_user_model().objects.first())
request.user.settings.dashboard_hide_age = None
context = {"request": request}
filter_data_age = cards._filter_data_age(context)
@ -50,7 +50,7 @@ class TemplateTagsTestCase(TestCase):
@mock.patch("dashboard.templatetags.cards.timezone")
def test_filter_data_age_one_day(self, mocked_timezone):
request = MockUserRequest(User.objects.first())
request = MockUserRequest(get_user_model().objects.first())
request.user.settings.dashboard_hide_age = timezone.timedelta(days=1)
context = {"request": request}
mocked_timezone.localtime.return_value = timezone.localtime().strptime(
@ -79,7 +79,7 @@ class TemplateTagsTestCase(TestCase):
@mock.patch("dashboard.templatetags.cards.timezone")
def test_card_diaperchange_last_filter_age(self, mocked_timezone):
request = MockUserRequest(User.objects.first())
request = MockUserRequest(get_user_model().objects.first())
request.user.settings.dashboard_hide_age = timezone.timedelta(days=1)
context = {"request": request}
time = timezone.localtime().strptime("2017-11-10", "%Y-%m-%d")
@ -292,7 +292,7 @@ class TemplateTagsTestCase(TestCase):
self.assertFalse(data["hide_empty"])
def test_card_timer_list(self):
user = User.objects.first()
user = get_user_model().objects.first()
child = models.Child.objects.first()
child_two = models.Child.objects.create(
first_name="Child", last_name="Two", birth_date=timezone.localdate()

View File

@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
from django.test import TestCase
from django.test import Client as HttpClient
from django.contrib.auth.models import User
from django.contrib.auth import get_user_model
from django.core.management import call_command
from faker import Faker
@ -23,7 +23,7 @@ class ViewsTestCase(TestCase):
"username": fake_user["username"],
"password": fake.password(),
}
cls.user = User.objects.create_user(is_superuser=True, **cls.credentials)
cls.user = get_user_model().objects.create_user(is_superuser=True, **cls.credentials)
cls.c.login(**cls.credentials)

View File

@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
from django.test import TestCase
from django.test import Client as HttpClient
from django.contrib.auth.models import User
from django.contrib.auth import get_user_model
from django.core.management import call_command
from faker import Faker
@ -24,7 +24,7 @@ class ViewsTestCase(TestCase):
"username": fake_user["username"],
"password": fake.password(),
}
cls.user = User.objects.create_user(is_superuser=True, **cls.credentials)
cls.user = get_user_model().objects.create_user(is_superuser=True, **cls.credentials)
cls.c.login(**cls.credentials)