Skip to content
Snippets Groups Projects
Commit afbcc956 authored by Frank Lange's avatar Frank Lange
Browse files

add user profile as extension to Django's user model

parent f9860201
No related branches found
No related tags found
No related merge requests found
......@@ -4,3 +4,7 @@ from django.apps import AppConfig
class DaliaConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'project.dalia'
def ready(self):
# Implicitly connect signal handlers decorated with @receiver.
import project.dalia.signals # noqa
# Generated by Django 5.1.7 on 2025-03-27 19:31
import django.db.models.deletion
import uuid
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0012_alter_user_first_name_max_length'),
]
operations = [
migrations.CreateModel(
name='UserProfile',
fields=[
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, primary_key=True, serialize=False, to=settings.AUTH_USER_MODEL)),
('dalia_id', models.UUIDField(default=uuid.uuid4, unique=True)),
('orcid', models.CharField(max_length=37)),
],
),
]
import uuid
from django.conf import settings
from django.db import models
# Create your models here.
class UserProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, primary_key=True)
dalia_id = models.UUIDField(default=uuid.uuid4, unique=True)
orcid = models.CharField(max_length=37) # "https://orcid.org/XXXX-XXXX-XXXX-XXXX"
from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
from project.dalia.models import UserProfile
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def initialize_user_profile_signal(sender, instance, created, **kwargs):
if created:
UserProfile(user=instance)
instance.userprofile.save()
from django.contrib.auth import get_user_model
from project.dalia.models import UserProfile
def test_initialize_user_profile_signal_initializes_user_profile_after_user_is_created(db):
user_model = get_user_model()
assert user_model.objects.count() == 0
user = user_model(username="test")
user.save()
assert user_model.objects.count() == 1
assert UserProfile.objects.count() == 1
assert user.userprofile.orcid == ""
assert user.userprofile.dalia_id
def test_initialize_user_profile_signal_does_not_change_profile_after_user_is_changed(db):
user_model = get_user_model()
user = user_model(username="test")
user.save()
assert user_model.objects.count() == 1
assert UserProfile.objects.count() == 1
orcid = user.userprofile.orcid
dalia_id = user.userprofile.dalia_id
user.first_name = "abc"
user.save()
assert user_model.objects.count() == 1
assert UserProfile.objects.count() == 1
assert user.userprofile.orcid == orcid
assert user.userprofile.dalia_id == dalia_id
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment