Fix not able to create users in admin by moving main-creation logic from manager's _create_user() to User's save().

This commit is contained in:
Casper V. Kristensen 2019-10-25 13:28:33 +02:00
parent 8da844d2e4
commit b3ba6caa07
Signed by: caspervk
GPG key ID: 289CA03790535054
3 changed files with 23 additions and 21 deletions

View file

@ -8,5 +8,3 @@ class CharacterForm(ModelForm):
model = Character
fields = ["name", "klass", "role"]
def clean_name(self):
return self.cleaned_data["name"].capitalize()

View file

@ -1,4 +1,4 @@
# Generated by Django 2.2.6 on 2019-10-25 01:58
# Generated by Django 2.2.6 on 2019-10-25 13:23
from django.conf import settings
import django.contrib.auth.validators
@ -55,7 +55,7 @@ class Migration(migrations.Migration):
migrations.AddField(
model_name='user',
name='main',
field=models.OneToOneField(on_delete=django.db.models.deletion.PROTECT, related_name='+', to='users.Character'),
field=models.OneToOneField(blank=True, on_delete=django.db.models.deletion.PROTECT, related_name='+', to='users.Character'),
),
migrations.AddField(
model_name='user',

View file

@ -12,22 +12,6 @@ class UserManager(DjangoUserManager):
avg_attendance=Avg("characters__raid_responses__attendance")
)
@transaction.atomic
def _create_user(self, username, email, password, **extra_fields):
if "main" not in extra_fields:
main = Character.objects.create(
user=None,
name=username,
klass=Character.WARRIOR,
role=Character.DAMAGE
)
main.save()
extra_fields["main"] = main
user = super()._create_user(username, email, password, **extra_fields)
extra_fields["main"].user = user
extra_fields["main"].save()
return user
class User(AbstractUser):
objects = UserManager()
@ -38,7 +22,8 @@ class User(AbstractUser):
main = models.OneToOneField(
"Character",
related_name="+",
on_delete=models.PROTECT
on_delete=models.PROTECT,
blank=True
)
class Meta:
@ -48,6 +33,22 @@ class User(AbstractUser):
if hasattr(self, "main") and self.main.user != self:
raise ValidationError({"main": "Main character must be owned by user."})
@transaction.atomic
def save(self, *args, **kwargs):
if not hasattr(self, "main"):
self.main = Character.objects.create(
user=None,
name=self.username,
klass=Character.WARRIOR,
role=Character.DAMAGE
)
self.main.save()
user = super().save(*args, **kwargs)
self.main.user = self
self.main.save()
return user
def avg_attendance(self):
return self.avg_attendance
@ -107,5 +108,8 @@ class Character(models.Model):
class Meta:
ordering = ["name"]
def clean(self):
self.name = self.name.capitalize()
def __str__(self):
return self.name