我正在尝试使用 VueJS 和 Django 以及 REST Api(通过 Axios 的 Ajax)制作博客。我可以在控制台中发送一个“PUT”请求而没有错误,但它不会影响数据库,链接方法没有被调用。我在默认情况下在 input type="file" 字段中设置已经上传的图像时也有问题。 代码:
Vuejs
<template>
<h1>ARTICOLO</h1>
<form @submit="onSubmit">
<input type="text" name="title" placeholder="Titolo" v-model="form.title">
<input type="text" name="desc" placeholder="Descrizione" v-model="form.desc">
<input type="text" name="category" v-model="form.category">
<input type="file" name="image" @change="EditImage">
<input type="text" name="author" v-model="form.author">
<input type="text" name="author" v-model="form.slug">
<textarea name="text" v-model="form.text"></textarea>
<p>{{ form }}</p>
<button type="submit" @click= "onSubmit">Edit</button>
</form>
</template>
<script>
import axios from 'axios';
import { getAPI } from '../api'
export default {
data () {
return{
Postslug: this.$route.params.Postslug,
form: {
title:"",
desc:"",
text:"",
category:"",
date:"",
author:"",
image:"",
slug:"",
},
selectedFile: ''
}
},
methods: {
EditImage(event){
this.selectedFile = event.target.files[0]
console.log(event);
},
// Form method
onSubmit(event){
const fd = new FormData();
fd.append('image', this.EditImage, this.EditImage.name)
event.preventDefault();
axios.put(`http://127.0.0.1:8000/blog/api/edit/${this.Postslug}`, this.form).then(response => {
this.form.title = response.data.title
this.form.desc = response.data.desc
this.form.text = response.data.text
this.form.image = this.fd
this.form.category = response.data.category
this.form.author = response.data.author
this.form.slug = response.data.slug
})
.catch(err => {
console.log(err)
})
},
},
created() {
getAPI.get(`blog/api/edit/${this.Postslug}`)
.then(response => {
this.form.title = response.data.title
this.form.desc = response.data.desc
this.form.text = response.data.text
this.form.date = response.data.date
this.form.image = response.data.image
this.form.category = response.data.category
this.form.author = response.data.author
this.form.slug = response.data.slug
})
.catch(err => {
console.log(err)
})
},
name: 'AdminEditArticle',
}
</script>
<style lang="sass" scoped>
</style>
Models.py
class Post(models.Model):
title = models.CharField(max_length=299)
author = models.ForeignKey(User,default=ANONYMOUS_USER_ID, on_delete=models.CASCADE)
category = models.ForeignKey(Category,default=ANONYMOUS_USER_ID, on_delete=models.CASCADE)
image = models.ImageField(blank=True)
desc = models.TextField()
text = RichTextField(blank = True, null = True )
date = models.DateTimeField(auto_now=False, auto_now_add=True)
slug = models.SlugField(null = True, blank = True, unique=True)
class Meta: # Order post by date
ordering = ['-date',]
def __str__(self): # Display title
return self.title
def get_absolute_url(self): # #TODO da cambiare
return reverse("listpost")
def save(self, *args, **kwargs): # Auto Slug Field
self.slug = slugify(self.title)
super(Post, self).save(*args, **kwargs)
Views.py
from Blog.models import *
from .serializers import *
from rest_framework.generics import *
# List data API for list of posts
class PostListApiView(ListCreateAPIView):
queryset = Post.objects.all()
serializer_class = PostListSerializer
# List data API for last 4 Posts publisced
class PostLastApiView(ListCreateAPIView):
queryset = Post.objects.all()[:4]
serializer_class = PostListSerializer
# Edit and delete datas in API for Posts
class PostEditApiView(RetrieveUpdateDestroyAPIView):
queryset = Post.objects.all()
serializer_class = PostDetailSerializer
lookup_field = "slug"
# Delete datas in API for Posts
class PostDeliteApiView(DestroyAPIView):
queryset = Post.objects.all()
serializer_class = PostDetailSerializer
lookup_field = "slug"
# Showthe data only for a element in Posts
class PostDetailApiView(RetrieveAPIView):
queryset = Post.objects.all()
serializer_class = PostDetailSerializer
lookup_field = "slug"
# Insert data in APi of Posts
class PostCreateApiView(CreateAPIView):
queryset = Post.objects.all()
serializer_class = PostDetailSerializer
lookup_field = "slug"
Axios
import axios from 'axios'
const getAPI = axios.create({
baseURL: 'http://127.0.0.1:8000',
timeout: 1000,
})
export { getAPI }
路由器
import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import SinglePage from '../views/SinglePage.vue'
import PostList from '../views/PostList.vue'
import Admin from '../views/Admin.vue'
import ArticleAdmin from '../views/ArticleAdmin.vue'
import AdminEditArticle from '../views/EditArticle.vue'
const routes = [
{ // HomePage Link
path: '/',
name: 'Home',
component: Home
},
{ // Article Detail Page Link
path: '/single',
name: 'SinglePage',
component: SinglePage,
},
{ // Article Page Link
path: '/articoli',
name: 'PostList',
component: PostList,
},
{ // Admin Page
path: '/admin',
name: 'Admin',
component: Admin,
},
{ // Admin Article List Page
path: '/admin/article',
name: 'AdminArticle',
component: ArticleAdmin,
},
{ // Admin Article Edit Page
path: '/admin/article/edit/:Postslug',
name: 'AdminEditArticle',
component: AdminEditArticle,
},
]
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes
})
export default router