初始化用户django,因此他有默认设置值

时间:2017-02-19 14:53:22

标签: django angular

我正在使用Django + Angular 2 。我正在创建用户,但他没有我想要的默认值...

模型

class Settings(models.Model):
    user = models.ForeignKey('auth.User', related_name='settings', on_delete=models.CASCADE)
    bolean1 = models.BooleanField(default=False)
    boolean2 = models.BooleanField(default=False)
    boolean3 = models.BooleanField(default=False)
    string1 = models.CharField(max_length=100, default='No description')

串行

class SettingsSerializer(serializers.ModelSerializer):
    class Meta:
        model = Settings
        fields = ('id', 'bolean1', 'bolean1', 'bolean3', 'string1')

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username', 'email', 'password' ,'settings', 'image')
        extra_kwargs = {'password': {'write_only': True}}

class CreateUserSerializer(serializers.ModelSerializer):  
    class Meta:
        model = User
        fields = ('email', 'username', 'password')
        extra_kwargs = {'password': {'write_only': True}}

    def create(self, validated_data):
        user = User(
            email=validated_data['email'],
            username=validated_data['username']
        )
        user.set_password(validated_data['password'])
        user.save()
        return user

视图

class SettingsValues(generics.ListAPIView):
    serializer_class = SettingsSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)

    def get_queryset(self):
        queryset = Settings.objects.all()
        queryset = queryset.filter(user=self.request.user.id)
        return queryset


class RegisterUser(generics.ListCreateAPIView):
    queryset = User.objects.all()
    serializer_class = CreateUserSerializer

问题在于,当我创建一个新用户时,他没有默认值,例如boolean 1,boolean 2等。我必须去django admin创建新设置并选择用户。

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

听起来像是KB167296,特别是FileTimeToSystemTime。您希望为每个创建的User()创建一个Settings - 您现在拥有默认值,但这只有在您保存{{1}时才有用模型。

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()

如果您的设置模型位于名为settings的应用中,那么您的设置/ apps.py应具有此功能 - Django's Signals

from django.apps import AppConfig

class SettingsConfig(AppConfig):
    name = 'settings'

    def ready(self):
        from . import signals

现在,只要创建了新的User,就会为它们创建Settings关系。

答案 1 :(得分:0)

我不确定这是否是你想要达到的目的,但试试这个。

//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)

preview 参考:django StackedInline

这将帮助您在用户模型结束时堆叠设置模型。这不会自动采用默认值,但会让您在创建用户模型时选择设置。