Add a photo - Django REST framework

I have two models, User and EcoUser, with a one-to-one relationship (I have omitted some fields for simplicity in this example):

class User(AbstractUser):
    picture_url = models.ImageField(upload_to='logos/', blank=True)

class EcoUser(models.Model):
    user = models.OneToOneField(User, related_name='eco_user')
    document = models.CharField(max_length=45, blank=True)

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

To handle the data of both tables with a single post or put request, I use a NestedSerializer. This allows me to update the data when registering without any issues:

Here is the serializer I use:

class EcoUserSerializer(serializers.ModelSerializer):

 user = UserSerializer(required=True)

 class Meta:
     model = EcoUser
     fields = '__all__'

 def update(self, instance, validated_data):
     instance.document = validated_data.get('document', instance.document)
     instance.save()
     user_data = validated_data.pop('user')
     user = instance.user
     user.picture_url = user_data.get('picture_url', user.picture_url)
     user.save()
     return instance

And in my viewset:

class EcoUserViewSet(viewsets.ModelViewSet):
    serializer_class = EcoUserSerializer
    queryset = EcoUser.objects.all()
    pagination_class = None
    parser_classes = (MultiPartParser,)

    @transaction.atomic
    def update(self, request, *args, **kwargs):
        with transaction.atomic():
            try:
                instance = self.get_object()
                instance.id = kwargs.get('pk')
                serializer = EcoUserSerializer(instance=instance, data=request.data)
                print(serializer)
                if serializer.is_valid(raise_exception=True):
                    self.perform_update(serializer)
                    return Response({"status": True, "results": "Data updated successfully"},
                                    status=status.HTTP_201_CREATED)
            except ValidationError as err:
                return Response({"status": False, "error_description": err.detail}, status=status.HTTP_400_BAD_REQUEST)

Everything was working fine until I added the ImageField and encountered a 400 bad request error when trying to update the data. I make this update request using Vue.js and Axios:

const bodyFormData = new FormData();
bodyFormData.append('user.picture_url', this.params.user.picture_url.name);
bodyFormData.append('document', this.params.document);
this.axios.put(`/users/${this.params.id}/`, bodyFormData, { headers: { 'Content-Type': 'multipart/form-data' } })
  .then((response) => {
    this.isSending = false;
    this.$snackbar.open(response.data.results);
  });

Is it correct to use user.picture_url as the field name in the append method? This is because picture_url is nested within the user object, and I need to update it accordingly.

Answer №1

During my investigation with the postman, I discovered the issue: The Django table's username field was required:

const formData = new FormData();
formData.append('user.picture_url', this.params.user.picture_url.name);
formData.append('document', this.params.document);
formData.append('user.username', this.params.username);

After making this adjustment, everything worked perfectly!

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

Is the ajax response not being sent back?

Hi! I'm currently working with the Django framework and facing an issue with the Ajax response. Below is the code snippet I have tried: def ForgotUsername(request): if request.method == "POST": email = request.POST['email'] ...

Utilizing Color with Nuxt and Vuetify: Enhancing Components such as v-toolbar

Hello, I need help with my Nuxt 2 and Vuetify 2 project. I want to customize a simple Vuetify v-toolbar component by giving it a specific color. The official documentation suggests using the following code: <template> <v-toolbar flat color=&q ...

The final DOM is not loading properly when using Jest and React Testing Library during page initialization

I'm currently working on testing my React application with Jest and React Testing Library. During this process, I am attempting to verify that the login page displays a specific message once it has fully loaded. Upon initial loading of the login page, ...

How should one go about creating an npm package out of a vuejs component and testing it locally?

Initially, I created a vuejs project as a test container using vue-cli. Next, I developed an npm package named "vue-npm-example" from a Vuejs component in my local environment and then imported it into the aforementioned testing project. Within the packag ...

Exploring the possibilities of utilizing React server components in my project

I am interested in experimenting with the new React API for making server-side component calls. However, I am unable to find any information on how to begin a project using server components. In an example of source code that I stumbled upon, it mentioned ...

The message will not appear to indicate whether the room is valid or not

Take a look at this create_session.php application: Application Upon opening the application, you will encounter a CourseId textbox. Enter 'info101' in the textbox and click submit. You should see all the features listed below. Without entering ...

Troubleshooting: Issues with Adding a New Row in Datatables using JQuery

CSS : <div class="datatable-header"> <button type="button" name="add" id="add" class="float-right btn btn-info">Add</button> </div> <div class="table-responsive"> <table ...

Bring back object categories when pressing the previous button on Firefox

When working with a form, I start off with an input element that has the "unfilled" class. As the user fills out the form, I use dynamic code to remove this class. After the form is submitted, there is a redirect to another page. If I click the "back" ...

Troubleshooting issue with React mapping an array of items in a modal window

My state implementation is working perfectly fine, except for a minor issue with the modal window. Within the state, I have utilized objects that are normally displayed (you can refer to the screenshot here). Please pay attention to the "Open modal" butt ...

What is the best method for retrieving the complete error message from my client-side Node and Express server?

When I send a request to my express route and it returns a 400 status along with an error message, I am facing an issue on the client-side. The alert message only displays "Object object" instead of the actual error message that I see on the server side. U ...

Change the function from onLoad to onClick exclusively

I'm experiencing a particle explosion on my webpage due to this code. I connected the onClick function to a button in my HTML so it executes only when that specific button is clicked. However, the function automatically runs when I load the HTML and ...

How to access a file stored within a proxy object using Vue.js

I am currently working on sending a file from a vue-page to the server. To achieve this, I have implemented the following: FileFrom component: <template> <div class="FileForm" v-bind:name="name"> <label clas ...

Tips for adjusting the size of Material UI icons

My Material UI icon size doesn't align naturally with the button: https://i.sstatic.net/l1G98.jpg Button code snippet: <Button variant="outlined" startIcon={<FacebookIcon />}> </Button> Here is the complete example ...

Should the header include individual CSS and JS files, or should all code be contained within a single CSS and JS file?

As I work on optimizing my website, I find myself juggling multiple plugins that include jQuery plugins with CSS along with my own JavaScript code. Currently, the CSS is spread across separate files for each plugin I have downloaded. When needed on a page ...

The action of POSTing to the api/signup endpoint is

Currently delving into the MEAN stack, I have successfully created a signup api. However, when testing it using POSTMAN, I encountered an unexpected error stating that it cannot POST to api/signup. Here is a snapshot of the error: Error Screenshot This ...

What is the best way to conduct tests on React components' methods and ensure they are integrated into my Istanbul coverage report

Is there a way to test the methods of react components and include them in my Istanbul test coverage? Edit: I'm using enzyme. Just wanted to mention that. Take, for instance, this component: class SearchFormContainer extends Component { static h ...

Is there a way for me to determine if a domain has been registered by the client?

I'm interested in creating a Web app that allows users to enter a domain name and then uses JavaScript to check its availability. I'm wondering if there's a method to do this without relying on my own hosting server. Is it possible to send a ...

Tips for utilizing the 'contains' feature within web elements with Java Selenium WebDriver?

In my current project, I am facing a challenge with two specific elements: one is a string formatted as ABC £12,56 and the other is a box called "Cashbox" that should be 15% of the value of the string. However, when attempting to locate the CSS for both e ...

How to get the initial item from an API using JavaScript mapping

When mapping my arrays, I usually use the following code: moviesList.map(movie => <MovieCard movieID={movie} key={movie} However, there are instances where my API returns multiple results. Is there a way to modify my .map function to display only t ...

How to retrieve properties of the final item in an array using Vue.js

Struggling with Vue.js JavaScript implementation. This is the current code: <div id="app"> <h1>Items</h1> <div v-for="item in items"> <input v-model="item.val"> </div> <button @click="addItem"> Ne ...