1

I'm working on a User Preferences viewset in DJANGO REST API in which a user can get a list of preferences along with updating the preferences. In Postman i can get the user's preferences, but when i go to 'put' i'm getting the following error: Integrity Error --NOT NULL constraint failed: pugorugh_userpref.age --any reason this might be happening?

The UserPref Model is below:

class UserPref(models.Model):
    user = models.ForeignKey(User)
    age = models.CharField(choices=AGE, max_length=7, default='b,y,a,s')
    gender = models.CharField(choices=GENDER_PREF, max_length=3, default='m,f')
    size = models.CharField(choices=SIZE_PREF, max_length=8, default='s,m,l,xl')

    def __str__(self):
        return '{} preferences'.format(self.user)


def create_user_preference(sender, **kwargs):
    user = kwargs['instance']

    if kwargs['created']:
        user_pref = UserPref(user=user)
        user_pref.save()

post_save.connect(create_user_preference, sender=User)

Here is my ViewSet:

class UserPrefViewSet(
    mixins.RetrieveModelMixin,
    mixins.UpdateModelMixin,
    viewsets.GenericViewSet):
    """View to get and update User Preferences."""
    permission_classes = (permissions.IsAuthenticated,)
    queryset = models.UserPref.objects.all()
    serializer_class = serializers.UserPrefSerializer

    # /api/user/preferences/
    @list_route(methods=['get', 'put'])
    def preferences(self, request, pk=None):
        user = request.user
        user_pref = models.UserPref.objects.get(user=user)

        if request.method == 'PUT':
            data = request.data
            user_pref.age = data.get('age')
            user_pref.gender = data.get('gender')
            user_pref.size = data.get('size')
            user_pref.save()

        serializer = serializers.UserPrefSerializer(user_pref)
        return Response(serializer.data)

and SERIALIZER

class UserPrefSerializer(serializers.ModelSerializer):
    extra_kwargs = {
        'user': {'write_only': True}
    }

    class Meta:
        fields = (
            'age',
            'gender',
            'size'
        )
        model = models.UserPref

1 Answer 1

1

Looks like PUT data doesnt contain age value. Since age field is not nullable, blank age value raise error. Try to fix this:

user_pref.age = data.get('age') or user_pref.age
...
user_pref.save()

this allows not to change age if value not in request data.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.