Trouble persisting Vue JS form data to Django Rest database

I am currently working on a project involving Django, Django REST, and Vue JS. I have successfully managed to retrieve information from the API to the Vue JS frontend. However, I am facing an issue where data is not being posted to the Django database when using the Vue JS frontend to submit a form after clicking the button. I have tried various solutions without success. Any assistance would be greatly appreciated. Thank you.

Below is my Vue code in 'AllNotes.vue':

<template>
  <div class="notes_container">
    <div class="add_note">
      <form v-on:@submit="submitForm">
        <div class="form-group">
          <label for="content">Content</label>
          <input
            type="text"
            class="form-control"
            id="content"
            v-model="content"
          />
        </div>

        <div class="form-group">
          <button>Add Note</button>
        </div>
      </form>
    </div>
    <div class="note_content">
      <h1>Tweets</h1>
      <ul class="note_list">
        <li v-for="note in notes" :key="note.id">
          <p>"{{ note.content }}""</p>
          <button @click="toggleNote(note)">
            {{ note.completed ? "Undo" : "Complete" }}
          </button>
          <button @click="deleteNote(note)">Delete</button>
        </li>
      </ul>
    </div>
  </div>
</template>


<script>
import axios from "axios";
export default {
  data() {
    return {
      notes: [],
      content: "",
    };
  },

  methods: {
    async getData() {
      try {
        // fetch tasks
        axios.get("http://localhost:8000/notes/").then((response) => {
          this.notes = response.data;
        });

        // set the data returned as tasks
      } catch (error) {
        // log the error
        console.log(error);
      }
    },
  },

  submitForm: function () {
    // Send a POST request to the API
    axios
      .post("http://localhost:8000/notes/", { note: this.content })

      .then((response) => {
        this.content = "";
        this.notes.push(response.data);
      });

    // Append the returned data to the tasks array

    // Reset the title and description field values.
  },
  created() {
    // Fetch tasks on page load
    this.getData();
  },
};
</script>

Here is the Django serializer:

from rest_framework import routers, serializers, viewsets
from post.models import *
# Serializers define the API representation.
class NoteSerializer(serializers.HyperlinkedModelSerializer):
    #journal_user = serializers.CharField(source="journal_user.username", read_only=True)
    class Meta:
        model = Note
        fields = ['id', 'content', 'publish_date']

Below is my view in Django:

#For our API View.
from rest_framework import  viewsets
from post.serializers import NoteSerializer
from rest_framework.parsers import JSONParser
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse, JsonResponse

class NoteViewSet(viewsets.ModelViewSet):
    queryset = Note.objects.all()
    serializer_class = NoteSerializer
    

    
@csrf_exempt
def notes(request):
    if request.method == 'GET':
        notes = Note.objects.all()
        serializer = NoteSerializer(notes, many=True)
        return JsonResponse(serializer.data, safe=False)
    elif request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = NoteSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data, status=201)
        return JsonResponse(serializer.errors, status=400)

Answer №1

Make sure to correct your syntax for event submission.

Instead of-

v-on:@submit="submitForm"

You can use either-

v-on:submit="submitForm"

Or-

@submit="submitForm"

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

Implementing dynamic loading with a Vue component loader

Is it possible to dynamically import a component using a default Loader if it's not loaded? Currently, we are using the following approach: import Dashboard from '../components/dashboard'; Vue.component('dashboard', Dashboard); ...

Peer dependency conflict encountered during installation of Bootstrap and Bootstrap-Vue

Encountering issues while trying to start a new Vue Bootstrap project. Here is my process and the errors I am facing, any suggestions? Unfortunately, Chat-GPT was not helpful, so now I'm turning to you for assistance :-) vue create my-project select ...

How can I use VueJS Cli to create a shared variable that is accessible across all pages and can be monitored for changes within a specific page?

Recently, I've delved into the world of VueJs and I'm encountering some issues with a project that I can't seem to resolve through online resources. I am trying to establish a variable that is common across all pages (month), and whenever t ...

Error message in vuejs: JSON parsing error detected due to an unexpected "<" symbol at the beginning

I have been trying to troubleshoot this issue, but I am having trouble understanding how to resolve it. Currently, I am using lottie-web in a project and need to set the animation parameters on an object in order to pass them as a parameter later. This i ...

Having trouble reaching the link using my controller in a jhipster application

I've been working on a project with jhipster and recently created a test controller to check if everything is functioning properly. Take a look at my test controller code: @RestController @Configuration public class TestController { private stat ...

Vue CLI's build process encounters issues specifically related to Bootstrap Vue Next

I am currently in the process of migrating an application from Vue 2 to Vue 3 using the composition API. In our previous version, we were utilizing Bootstrap, but after some research, I discovered that it would be more suitable to switch to bootstrap-vue- ...

Django - the decision to save a model instance

Having two Django models, ModelA and ModelB, where the latter contains a foreign key relationship to the former. class ModelA(models.Model): item = models.BooleanField(default=True) class ModelB(models.Model): modela = models.ForeignKey(ModelA) ...

What is the best way to update a Vue.js input element using JavaScript?

Looking to use a Vue.js input for automated testing purposes. How can I successfully set a value and submit it without it being automatically changed back to default data? I have tried the following method to set the value, but it keeps getting overridden ...

Using Vue.js to conditionally render content based on changes in a variable

I am facing a challenge in rendering a new element once the boolean variable waiting changes to true. The issue arises when transitioning from one v-if statement to another, as the boolean does not update until the first statement is completed. How can I s ...

What is the best method for exchanging data between two Vue instances?

index.html <script defer src='main.js'></script> <script defer src='extension.js'></script> <div id='main-app'></div> <div id='extension'></div> main.js const store ...

Toggle button in VueJS that dynamically shows/hides based on the state of other buttons

In my table, I have included options for the days of the week such as Everyday, Weekdays, and Weekend. Each row contains 2 select items to choose start and end times for updates. Additionally, there is a toggle button at the end of each row that enables or ...

Axios AJAX request failing to pass parameter

Vuejs is my go-to frontend framework for building projects. When creating a component called ('TimeCapsy.vue'), I initiate an AJAX call to the backend in this manner: created: function () { if (verify.verify_login()) { let tok ...

The IP validation feature in the textbox is not performing as anticipated

My goal is to have a textbox that receives an IP address and validates it before submission. To achieve this, I've developed a JavaScript class called `validityCheck`. In my main Vue.js component, I aim to utilize this class to validate the input&apo ...

I am attempting to show a message using v-model, however, it seems to be malfunctioning

I am currently learning how to use Vue.js with Laravel. However, I am encountering an issue when trying to display a message in an input tag using v-model. <div class="card" id="myAppId"> <p>@{{ message }}</p> <input type="text" v-mod ...

Unexpectedly, the npm watch command ceased functioning on WSL

I have a Symfony and Vue project that I develop locally using WSL 2. Lately, when I run npm run watch, it executes encore dev --watch successfully but does not update when I make changes to the code. It was working fine before, so I suspect it stopped work ...

Unable to instantiate a Vue reference with a potential null type

When working in Vue v3, I encountered a situation where I needed to create a ref with a type that could possibly be null. This specific scenario in my app involves data that starts off as null and then gets populated after loading completes. Just to illus ...

Why does Vue 3 template display 101 instead of 1 when incrementing the number from 0?

Vue.createApp({ data() { return { counter: 0 } }, template: '<div>{{counter++}}</div>' }).mount('#root') Ultimately, the code above displays the number 101 on the page. Any insights into why this is happ ...

Vue.js V-for not rendering any content

I am currently working on populating an array with objects retrieved from an API. The objects are being fetched successfully, but I am facing issues when trying to display them using v-for in the array. Below are my data variables: data() { return { ...

what is the most effective method for integrating Vue with Express?

1: I have successfully installed expressjs on my system. 2: Following that, I used npm to install the vue framework by running 'npm install vue --save'. 3: Additionally, I utilized handlebars as the template-engine for expressjs. In my index.hbs ...

Avoiding substantial sections during execution of the command "Npm run build"

Encountering an issue when attempting to execute "npm run build" (!) Encountered chunks larger than 500 KiB after minification. Suggestions: - Implement dynamic import() for code-splitting the application - Utilize build.rollupOptions.output.ma ...