Storing the many-to-many field when creating an object in Django DRF

Excuse me if this may seem like a straightforward question. I have looked for various solutions, but none of them seem to address my specific issue.

I am dealing with a model that has a many-to-many field relationship. Whenever I create a new object through the DRF REST API, the regular fields of the object (model) get saved correctly, but the many-to-many related field remains empty.

This is my model with the many-to-many related field:

class CustomerProfile(models.Model):
    ...
    stores = models.ManyToManyField(Store) # <- the related field
    first_name = models.CharField(max_length=30, blank=True)
    last_name = models.CharField(max_length=30, blank=True)
    email = models.EmailField(max_length=60, blank=True)
    phone = models.CharField(max_length=15, blank=True)

    def __str__(self):
        return str(self.first_name)

And here is the related (store) model:

class Store(models.Model):
    store_name = models.CharField(max_length=30, unique=True, null=True)
    ...
    
    def __str__(self):
        return str(self.store_name)

This is my serializer:

class CustomerSerializer(serializers.ModelSerializer):
    stores = StoreSerializer(read_only=True, many=True)

    class Meta:
        model = CustomerProfile
        fields = ['stores', 'first_name', 'last_name', 'email', 'phone']

This is my view:

class CustomerCreate(generics.CreateAPIView):
    queryset = CustomerProfile.objects.all()
    serializer_class = CustomerSerializer

Here is my POST request:

axios({
    method: "POST",
    url: this.api_base_url + "api/.../customer_create/",
    data: {
        first_name: 'Tom',
        last_name: 'Hardy',
        email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dcb2bdb1b99cbbb1bdb5b0f2bfb3b1">[email protected]</a>',
        phone: '01234567898',
        stores: ['store_name',], // this is the store I want to link the customer to
    }
})

Even though an object is created when I make a POST request to this endpoint, the stores array always ends up being empty.

Outcome:

data:
  email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="89e7e8e4ecc9eee4e8e0e5a7eae6e4">[email protected]</a>"
  first_name: "Tom"
  last_name: "Hardy"
  phone: "08038192642"
  stores: []

What is the correct way to add the stores in this scenario?

Answer №1

class ClientSerializer(serializers.ModelSerializer):
    locations = serializers.PrimaryKeyRelatedField(queryset=Location.objects.all(), write_only=True, many=True)

    class Meta:
        model = ClientProfile
        fields = ['locations', 'first_name', 'last_name', 'email', 'phone_number']

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

In search of a reliable file-upload solution for Django's admin interface

I am in need of a file uploader for various uses. The admin-backend user should have the ability to upload files from any location within the admin site and share links to these files with other applications. I'm sure this idea has crossed someone el ...

Utilizing Javascript to interact with GroupMe API through POST method

I've been working on creating a client for GroupMe using their provided API, but I'm stuck and can't seem to figure out what's going wrong. curl -X POST -H "Content-Type: application/json" -d '{"message": { "text": "Nitin is holdi ...

Monitor modifications to the form as the user navigates away from the page or refreshes

Currently, I am working on a form that was created using Formik and React Hooks. I would greatly appreciate any suggestions on how to track changes made to the form when a user clicks the home button or refreshes/reloads the page. I attempted to use the b ...

Is it possible to use Koajs without needing to include the --harmony tag?

Following the merge of iojs into Node, I assumed that I could run koajs without the need for the --harmony tag (as it would have support for generators from es6). Inside my server.js file, I have the following code: var koa = require('koa'); va ...

Sharing functions between Angular components

Check out my problem statement: https://stackblitz.com/edit/angular-jk8dsj I'm facing two challenges with this assignment: I need to dynamically add elements in the app.component when clicking a button in the key-value.component. I've tried ...

Modify the color of the field that is currently chosen

Is there a way to modify the highlight color of the active record in an extjs combobox? In the image provided below, the record Petty Cash Fund is currently selected in my dropdown, but the highlighting is not very visible. How can I adjust this for all co ...

Is it considered poor practice to develop my own authentication backend in Django?

Currently, I am working on setting up a custom authentication backend in Django. Although my custom Auth model and custom user creation form are functioning properly, I encountered an issue when attempting to log in using my custom authentication backend. ...

Unable to retrieve context value for authentication requirements

I have implemented a feature in my application where I redirect users to the login page for certain special pages if they are not logged in. The implementation involves using react-router. Here is the code snippet for my RequireAuth component: const Requir ...

What is the best way to paginate aggregated results in Mongoose?

In my project, I have a User model that is linked to two other associated models - Profile and WorkProfile. The Profile model contains basic information about the user like name, email, and home address, while the WorkProfile model stores details such as o ...

The Jquery click event refuses to trigger

Below is the JavaScript code that is not functioning: $('#change-priority-modal').find('.btn-primary').unbind().on("click", function () { //my_func_body } Interestingly, the code works perfectly fine in the developer console. I would ...

The JSX function seems to be malfunctioning, as the function part is not displaying on the webpage as intended

This code snippet is a part of a React component in a project. I have imported a CSS file for styling and have already integrated Material UI. However, the function for the new article is not displaying on the webpage as expected. import "./Widgets. ...

Guide on receiving application/csp-report as json in an express application utilizing bodyParser

I am currently working on creating a middleware that can receive CSP reports from browsers. Browsers send these reports with the Content-Type of application/csp-report, and the data is in JSON format. Right now, I'm using bodyParser.text to handle thi ...

How can I return a customized error response from a Django Rest Framework serializer?

I am facing an issue with sending a custom response from the create view of my serializers to the front-end of my application. I have tried following tutorials on rest framework Response but it seems not to be working. Here is a snippet of my code: clas ...

Creating a Fresh Row with Form Inputs and a PHP Variable

I am working on a table where pressing a button adds a new row. Here is the code snippet: <table id='editTable' width='655' border='1'>"; <tr><th width='330' align='left'>Expense Descript ...

In Python, a dictionary is like a JSON object but with an additional curly bracket, which can be accessed through HttpResponse

I need to transfer a specific JSON data via a GET request to a Python Django server. The structure of the JSON is shown below. data = { test1: [1, 2, 3, 4], test2: { test21: ['a', 'b'], ...

An unusual issue encountered while utilizing jQuery toggle: a straightforward illustration

Attempting to create a partial fade effect using toggle for toggling opacity values when clicking an element, but encountering an issue where nothing happens on the first click. The HTML code: <html> <head> <script type="text/javascript" s ...

The issue arises when I try to retrieve information from MySQL using Ajax, as it appears

I am currently working on developing an ecommerce website. In order to display products, I am fetching data from a database. My goal is to allow users to add products to their cart without having to refresh the page. I have attempted to use AJAX for this ...

When using PyCharm, auto-imports may not recognize the Django project name

When using PyCharm, you have the ability to automatically import a class that is not detected within the current file. For example, if you input a method or class name that is not found in the file, PyCharm will insert an import statement for it. However, ...

What are the potential risks associated with including your backend server port number in your code?

Working on a project using React and Node.js here. My server is set up with Express and the dotenv package to keep my server configurations secure, like the PORT number where my backend server operates. For instance, my server's environment variable i ...

How can you apply the CSS styles of your grandparents without inheriting the styles of

Although it may seem unlikely, I still wanted to inquire about the possibility. <body> //body with 'back' background <div id="div1"> //div1 with 'front' background <div id="child1"> //c ...