Creating a user within a nested serializer in Django Rest Framework

Hey everyone, I'm currently working on creating a user via API using nested serializers in Django Rest Framework and running into some issues. Here's the code snippet:

class AffiliateRegisterSerializer(serializers.ModelSerializer):

    class Meta:
        model = Affiliate
        fields = ('phone', 'address', 'state', 'city', 'ZIP', 'country', 'company', 'web_name', 'web_url', 'web_desc', 'payee_name', 'monthly_visits',)

And here's my second serializer:

class UserSerializer(serializers.ModelSerializer):

    '''
    Registering a new user with Affiliate Profile
    '''

    affiliate = AffiliateRegisterSerializer(required=False)

    class Meta:
        model = User
        fields = ('username', 'first_name', 'last_name', 'email', 'password', 'affiliate',)
        write_only_fields = ('password',)
        read_only_fields = ('id', 'affiliate',)

    def create(self, validated_data):
        affiliate_data = validated_data.pop('affiliate')
        user = User.objects.create_user(**validated_data)
        Affiliate.objects.create(user=user, **affiliate_data)
        return user

Now, moving on to the view:

class AffiliateSignUp(generics.CreateAPIView):
    '''
    API endpoint for Affiliate Users registration
    '''

    queryset = User.objects.all()
    serializer_class = UserSerializer
    permission_classes = [permissions.AllowAny]

    @method_decorator(ensure_csrf_cookie)
    @method_decorator(csrf_protect)
    def create(self, request):
            serializer = UserSerializer(data=request.data)

            if serializer.is_valid():
                    serializer.save()
                    return JsonResponse(serializer.data, status=201)
            return JsonResponse(serializer.errors, status=400)

I'm looking to send a POST request via AngularJS to instantly create the user and profile. How can I accomplish this?

When attempting to POST a nested object via AngularJS, I encounter the following error message:

Affiliate field is required.

While registering the user directly through the backend works fine by visiting /api/affilaite URL, the challenge lies in sending the POST request with a nested object in JavaScript. Any insights on how to tackle this would be greatly appreciated.

Here is the excerpt of my javascript code:

data:$httpParamSerializerJQLike({
                'first_name':$scope.userData['first_name'],
                'last_name':$scope.userData['last_name'],
                'username':$scope.userData['username'],
                'password':$scope.userData['password'],
                'email':$scope.userData['email'],
                affiliate:{
                'phone':$scope.userData['phone'],
                'address':$scope.userData['address'],
                'state':$scope.userData['state'],
                'city':$scope.userData['city'],
                'ZIP':$scope.userData['ZIP'],
                'country':$scope.userData['country'],
                'company':$scope.userData['company'],
                'web_url':$scope.userData['webUrl'],
                'web_name':$scope.userData['webName'],
                'web_desc':$scope.userData['webDesc'],
                //'web_category':$scope.userData ['webCategory'],
                'payee_name':$scope.userData['payeeName'],
                'monthly_visits':$scope.userData['monthly_visits']
                }
              }

I need your help on this matter, any advice or suggestions are welcome! Thank you :)

Answer №1

The affiliate field is set as read-only in the Meta serializer with the following code:

read_only_fields = ('id','affiliate',)
.

Read-only Fields

Fields marked as read-only are visible in the API output, but cannot be modified during creation or update operations. Any attempt to include 'read_only' fields in serializer input will be disregarded.

To make sure a field is used for serialization but not for deserialization (creation or updating instances), set this option to True.

By default, it is set to False.

Answer №2

SUCCESSFULLY RESOLVED

The issue stemmed from sending a QueryDict in application/x-www-form-urlencoded format.

To rectify this, I made the following adjustments in the front-end code:

method:'POST',
            url:'/api/URL/',
            headers: {'Content-Type': 'application/json'},
            dataType: 'json',

I then sent a nested object instead.

This resulted in the immediate creation of a user with a user profile attached.

A big thank you to everyone for the assistance!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering a parsererror with $.ajax while processing JSON that includes a new Date() object

After fetching JSON from a MongoDB database, I serialize it and send it back to the JavaScript client using a $.ajax call. Here is an example of the $.ajax call: function server_request(URL, httpMethod, dataObject) { var output = ""; var typeofD ...

Using the power of node.js to iterate through a loop of queries and execute

While I am running a for loop, within the loop itself I am executing a PostgreSQL query and storing the result in an array. However, I am unable to determine the order of execution. Here is my code: var array =[]; for(var i = 0 ; i< latitude.le ...

Combine two arrays in MongoDB where neither element is null

Issue I am looking to generate two arrays of equal length without any null elements. Solution I have managed to create two arrays, but they contain some null values. When I remove the null values, the arrays are no longer of equal length. aggregate([ ...

Guide on NodeJS: Harnessing the power of nested functions to ensure synchronous execution

Imagine two functions, A and B, both interacting with a MySQL database using connection.query(...) methods. Function A utilizes a while loop to navigate through the response it receives. Subsequently, function B is invoked with the response from function ...

What is the best way to include and control persistent URL parameters when making Ajax requests?

Imagine having two different resource lists on your website: one for users and the other for groups. As you navigate through each list in increments of 10, it's important to preserve the state of the list so that when you share the URL with someone el ...

Assign position values to an element inside a DIV container using JavaScript, Cascading Style Sheets, and

I am currently creating some visual representations of journal issues. I am looking to showcase blocks of text using basic DIVs or other elements inside another DIV, mirroring the organization of the issue page. In order to achieve this, I need to positi ...

My router-outlet is malfunctioning when trying to display my component

I am currently diving into learning Angular 2 in order to revamp my personal website. However, I've encountered an issue where my application fails to load the component when I navigate to the appropriate route by clicking on the navigation bar. Insi ...

What is the best way to implement a toggle feature for a single image within a div element that contains multiple images when clicked?

I am facing an issue where I have multiple images stacked on top of each other. When one of the images is clicked, I want a toggle function to activate that changes the opacity of the top image to 0, revealing the image underneath. However, every time I cl ...

Testing the performance of MEAN applications under heavy load

As I work on developing an application using the cutting-edge MEAN stack, I have successfully deployed the initial version to a server. This application comprises of a static HTML file (along with CSS and some images) as well as numerous JavaScript files. ...

Is there a way to enable code completion for Firebase on VS Code?

After successfully setting up Typescript for code completion following the guidelines provided in this resource, I now want to enable code completion for Firebase in VS Code. However, I am unsure of the steps to achieve this. How can I activate code compl ...

Organization of a Project using Silex and Angular JS 2

After successfully creating a small app using Angular 2 and REST APIs, I am now interested in incorporating both the backend and frontend into a single project. I am currently exploring Silex as a potential solution to build an application with Angular 2 ...

What is the proper way to include "arr[i]" within a for loop?

How can I include "arr[i].length" in my FOR LOOP? Using arr[0].length works correctly, but when using just "i" it throws an error. My goal is to iterate through a 2D array. function calculateSum(arr) { var total = 0; for (let i = 0; i < arr[i] ...

Utilizing typesafe trpc in Node.js to efficiently transfer data between routes

I have successfully implemented an end-to-end typesafe API using the T3 Stack and can access all the data and types in my Next.js app. However, I also have a Node.js backend to populate my database with. My Node.js setup is as follows: app.use( '/t ...

The POST method responds with an error message stating that the "GET" method is not permitted

The concept behind the project involves generating a unique code when creating a room to avoid duplicates and ensuring that the host can create their own name. Although I have created the room and implemented a random code generation system, I am encounte ...

Watch an object with AngularJS's $scope and detect and respond only to changes in its property values

Currently, I am monitoring scope changes using a simple watch like this: $scope.$watch('myObject', function(newValue, oldValue) { if (newValue !== oldValue) { return newValue; } }, true); In this case, myObject is an ordinary ob ...

Troubleshooting problem involving Socket IO synchronization

I have successfully integrated a website chat using python-socketio and socket.io-client. However, a syncing issue arises when multiple tabs are opened simultaneously in different browsers or incognito sessions with the same logged-in user. The newly open ...

Attempting to capture a previously unhandled error thrown by Axios when utilized in conjunction with React Query (with suspense mode enabled) within a NextJs application

Utilizing NextJS, React query (with axios and suspense mode), I am attempting to handle an intentional 404 error from my API. Although I successfully caught it in my error.js file, the same error still shows up in the console as "uncaught." https://i.stack ...

Mastering the AngularJS Inheritance Function

Looking for a solution: I'm working with AngularJS and have 5 controllers. I want all the children controllers to inherit the functions of the parent controller, such as datetimepicker and autorefresh. I attempted using rootscope but haven't foun ...

Employing VAutocomplete component from vuetify in combination with a render function (scoped slot)

Trying to implement the Autocomplete component within a render function but encountering issues with the scopedSlots feature. Here is my code snippet: import { VAutocomplete } from 'vuetify/lib' export default { render (h) { return ...

There seems to be an issue with the functionality of the Bootstrap Modal

I've been working on incorporating bootstrap login Modal functionality into my code, but for some reason, the screen is not displaying it. Here's what shows up on the screen: https://i.sstatic.net/UIU2w.png The red box in the image indicates whe ...