Vue表单数据无法提交至Django Rest数据库问题求助
问题描述
我正在开发一个基于Django、Django Rest Framework和Vue.js的项目,目前能正常从API获取数据到Vue前端,但点击按钮提交表单时,数据无法存入Django数据库。尝试多种方法均无效,求帮助。以下是相关代码:
Vue组件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 { axios.get("http://localhost:8000/notes/").then((response) => { this.notes = response.data; }); } catch (error) { console.log(error); } }, }, submitForm: function () { axios .post("http://localhost:8000/notes/", { note: this.content }) .then((response) => { this.content = ""; this.notes.push(response.data); }); }, created() { this.getData(); }, }; </script>
Django序列化器代码
from rest_framework import routers, serializers, viewsets from post.models import * class NoteSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Note fields = ['id', 'content', 'publish_date']
Django视图代码
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)
问题修复方案
1. 阻止表单默认提交行为
表单提交会触发页面刷新,中断axios请求。修改表单标签,添加默认行为阻止:
<form @submit.prevent="submitForm">
2. 修正POST请求的字段名
Vue中发送的{ note: this.content }与序列化器要求的content字段不匹配,修改请求数据结构:
submitForm: function () { axios .post("http://localhost:8000/notes/", { content: this.content }) .then((response) => { this.content = ""; this.notes.push(response.data); }) .catch(error => { console.error("提交失败详情:", error.response.data); // 添加错误日志,方便排查 }); }
3. 检查模型字段必填项
确认Note模型中的publish_date字段是否设置了auto_now_add=True或默认值,如果是必填且无默认值,需要在序列化器中添加对应处理,或者修改模型字段允许为空。
4. 确认路由配置
确保项目路由指向的是notes函数视图(而非NoteViewSet),避免路由冲突导致请求未被正确处理。
内容的提问来源于stack exchange,提问作者robert
相关产品推荐
相关产品推荐

