1👍
✅
Sounds like you want Django’s Signals, specifically post_save
. You’ll want to create a Settings()
for each User()
that’s created – you have default values right now, but that only helps when you’ve saved the Settings
model.
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth import get_user_model
User = get_user_model()
@receiver(post_save, sender=User)
def create_settings(sender, instance, created, **kwargs):
# Only create a Settings relation if the User is new
if created:
settings = Settings(user=instance)
settings.save()
If your Settings model is in an app called settings
, then your settings/apps.py should have this – good StackOverflow answer on this:
from django.apps import AppConfig
class SettingsConfig(AppConfig):
name = 'settings'
def ready(self):
from . import signals
Now, whenever a new User
is created, a Settings
relation is created for them as well.
0👍
I am not sure if this is what you want to achieve, but try this.
//admin.py
from django.contrib import admin
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin
from accounts import models
admin.site.unregister(User)
class UserRoleInline(admin.StackedInline):
model = models.UserRole
class UserRoleAdmin(UserAdmin):
inlines = [UserRoleInline]
admin.site.register(User, UserRoleAdmin)
//model.py
from django.db import models
from django.contrib.auth.models import User
class RoleType(object):
MANAGER = 'm'
CANDIDATE = 'c'
CHOICES = ((MANAGER, 'Manager'), (CANDIDATE, 'Candidate'))
class UserRole(models.Model):
user = models.OneToOneField(User)
role = models.CharField(max_length=1, choices=RoleType.CHOICES)
Reference: django StackedInline
This will help you stack the setting models at end of User model. This won’t automatically take a default value, but will let you choose the settings as the user models is created.
- Python_Django – Adding Attending Event option – How to?
- How to properly refactor this function into another file? django
- Secure URL/page for AnonUser to update a model field – Django Rest framework
- Django CMS Placeholder Within Template Block Not Displaying
Source:stackexchange.com