作业讲解

2

html

<!--图书价格排序 start-->
<div id="books">
    <button @click="filter">价格排序</button>
    <ul>
        <li v-for="book in book_list">
            <h2>{{book.name}}</h2>
            <h2>{{book.price}}</h2>
        </li>
    </ul>
</div>
<!--图书价格排序 end-->

js

let vm5 = new Vue({
    el: '#books',
    data: {book_list: [], ordering: 'price',},
    created() {
        axios.get('http://127.0.0.1:8000/books/').then(res => {
            this.book_list = res.data
        })

    },
    methods: {
        filter() {
            if (this.ordering.indexOf('-') >= 0) {
                this.ordering = 'price'
            } else {
                this.ordering = '-price'
            }
        }
    },
    watch: {
        ordering() {
            axios.get('http://127.0.0.1:8000/books/?ordering=' + this.ordering).then(res => {
                this.book_list = res.data
            })
        }
    }

})

urls

from app01 import views
from rest_framework.routers import SimpleRouter
router = SimpleRouter()
router.register('books',views.BookView,'books')
urlpatterns = [

]
urlpatterns+=router.urls

views

from django.shortcuts import render, HttpResponse
from rest_framework.response import Response
import json
from rest_framework.viewsets import ViewSetMixin, GenericViewSet
from rest_framework.generics import ListAPIView
from .models import Book
from .serializer import BookSerializer
from rest_framework.filters import OrderingFilter
class BookView(ViewSetMixin, ListAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer
    filter_backends = [OrderingFilter]
    ordering_fields = ['price']

    def list(self, request, *args, **kwargs):
        res = super().list(self, request, *args, **kwargs)
        res.headers['Access-Control-Allow-Origin'] = '*'
        return res

model

from django.db import models
class Book(models.Model):
    name=models.CharField(max_length=32)
    price=models.IntegerField()

serializer

from rest_framework import serializers
from .models import Book
class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = '__all__'

3和4和5

html

<!--返回图片地址start-->
<div id="picaddr">
    <hr>
    <queque @looook="pokemon"></queque>
    <hr>
    <h1>父亲</h1>
    <input type="text" v-model="address">
    <input type="file" @change="handleFileUpload">
    <button @click="uploadFile">上传文件</button>
</div>
<!--返回图片地址end-->

js

var queque = {
    template: `
      <div>
      <button class="btn btn-danger" @click="getpicaddr">猜猜我是谁</button>
      <button class="btn btn-info" @click="sendpicaddr">图片地址送到父亲那里</button>
      <img :src="url" alt=""></div>`,
    data() {
        return {url: 'https://img1.baidu.com/it/u=902574563,3188974570&fm=253&fmt=auto&app=120&f=JPEG?w=200&h=200',}
    },
    methods: {
        getpicaddr() {
            axios.get('http://127.0.0.1:8000/picture/').then(res => {
                this.url = res.data.pic
            })
        },
        sendpicaddr() {
            this.$emit('looook', this.url)
        }
    }
}
let vm6 = new Vue({
    el: "#picaddr",
    components: {
        queque
    },
    data: {address: '', file: '',},
    methods: {
        pokemon(url) {
            this.address = url
        },
        handleFileUpload(event) {
            this.file = event.target.files[0];
        },
        uploadFile() {
            let formData = new FormData();
            formData.append('file', this.file);
            // 添加其他表单数据
            // formData.append('name', '张三');
            // formData.append('age', '18');

            // 发送文件到后端
            axios.post('http://127.0.0.1:8000/upload/', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
            })
                .then(response => {
                    console.log(response.data);
                })
                .catch(error => {
                    console.log(error);
                });
        }
    }



})

urls

# 想让外部访问media就要开启media访问
from django.views.static import serve
from django.conf import settings
urlpatterns = [
    path('picture/', views.picture),
    path('media/<path:path>', serve,{'document_root':settings.MEDIA_ROOT}),
    path('upload/', views.upload, name='upload'),
]

settings

import os
MEDIA_ROOT=os.path.join(BASE_DIR,'media')

view

def picture(request):
    # res = {'pic':'https://img1.baidu.com/it/u=3878711869,2835723717&fm=253&fmt=auto&app=138&f=JPEG?w=200&h=200'}
    res = {'pic': 'http://127.0.0.1:8000/media/img/img.png'}
    response = HttpResponse(json.dumps(res))
    response['Access-Control-Allow-Origin'] = '*'
    return response

5 上传图片

view

@csrf_exempt
def upload(request):
    if request.method == 'POST' and request.FILES.get('file'):
        uploaded_file = request.FILES['file']
        # 保存文件到服务器
        with open('media/img/' + uploaded_file.name, 'wb+') as destination:
            for chunk in uploaded_file.chunks():
                destination.write(chunk)
        response = JsonResponse({'success': True})
        response['Access-Control-Allow-Origin'] = '*'
        return response
    else:
        response = JsonResponse({'success': False})
        return response


'''我们定义了一个MyFileUploadHandler类,继承自FileUploadHandler类。这个类可以用来处理文件上传请求,我们在这里不做任何处理,只是为了让Django能够正确处理文件上传请求。

在upload函数中,我们首先判断请求方法是否为POST,并且是否存在名为file的文件数据。如果存在文件数据,我们可以通过request.FILES['file']来获取上传的文件对象。

接着,我们使用open()函数打开一个文件,将上传的文件数据写入到这个文件中。在这个例子中,我们将文件保存到了uploads/目录下,文件名与上传的文件名相同。

最后,我们返回一个JSON格式的响应,表示文件上传是否成功。需要注意的是,我们在Django的视图函数中添加了@csrf_exempt装饰器,表示这个视图函数允许跨站请求伪造(CSRF)攻击。这是因为在文件上传时,需要提交表单数据,而表单数据中包含了CSRF令牌,如果没有添加这个装饰器,就会出现CSRF验证失败的错误。
'''

js

// 当用户点击上传文件按钮时,我们创建一个FormData对象,并将文件数据添加到其中。如果有其他表单数据也需要上传,可以通过formData.append()方法将其添加到FormData对象中。

// 最后,我们使用axios库的post方法将FormData对象发送到后端。需要注意的是,我们需要在请求头中设置Content-Type字段为multipart/form-data,表示这是一个包含文件数据的表单数据
posted @ 2023-06-08 16:56  雀雀飞了  阅读(11)  评论(0编辑  收藏  举报