0

I am using Django + Angular 2 . I am creating a user fine but he does not have the default values i want...

Model

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

Serializer

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

Views

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

The problem is that when i create a new user he does not have default values,e.g boolean 1, boolean 2 etc. i must go to django admin create new setting and choose the user.

Any idea ?

2 Answers2

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.

Community
  • 1
  • 1
Jens Astrup
  • 2,415
  • 2
  • 14
  • 20
  • You _can_ add it anywhere, but most people keep it in a separate signals.py file. In your case, it can be in the same module where your models.py is. You also have to add an import to your AppConfig, which I'll add to my answer now – Jens Astrup Feb 19 '17 at 15:12
  • i created a file signals.py and write the code inside apps.py but i have an error import .signals ^ SyntaxError: invalid syntax –  Feb 19 '17 at 15:18
  • Oh derp, sorry - `from . import signals` – Jens Astrup Feb 19 '17 at 15:20
  • thank you very much my friend! the only thing you forgot was to import model setting! perfect answer! –  Feb 19 '17 at 15:28
  • Ah true, haven't gotten through my coffee yet :) – Jens Astrup Feb 19 '17 at 15:28
  • one more question please. in my angular the service method pass username, email, password and settings. settings what should be ? an object with booleans ? if tried but it shows an error saying "{"settings":["Incorrect type. Expected pk value, received dict."]}" –  Feb 19 '17 at 15:45
  • 1
    Take a look at [writable nested serializers](http://www.django-rest-framework.org/api-guide/relations/#writable-nested-serializers) for DRF. – Jens Astrup Feb 19 '17 at 15:49
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)

preview 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.

Prashant Nair
  • 306
  • 3
  • 9