我想在Django上传图像。我成功地保存了其他领域的数据。但图像不上传。无法上传图像Django休息框架工作
我的模型:
from django.db import models
from account.models import Account
# Create your models here.
class Question(models.Model):
question_id = models.AutoField(primary_key=True)
user_id = models.ForeignKey(Account,db_column='account_id',on_delete=models.CASCADE)
type = models.CharField(max_length = 50 ,default= 'General')
location = models.CharField(max_length =50,default='Dhaka')
header = models.CharField(max_length =200)
details = models.CharField(max_length=500)
date_time = models.DateTimeField(auto_now_add=True)
vote = models.IntegerField(default=0)
hidden_flag = models.BooleanField(default=False)
anonymous = models.IntegerField(default=1)
image_1 = models.ImageField(blank=True,default='',upload_to='questions/')
image_2 = models.ImageField(blank=True,default='',upload_to='questions/')
我的串行:
from rest_framework import serializers
from .models import Question
class QuestionSerializer(serializers.ModelSerializer):
class Meta:
model = Question
fields = ('question_id', 'user_id', 'type', 'location', 'header', 'details', 'date_time','vote','hidden_flag','anonymous','image_1','image_2')
read_only_fields = ('question_id',)
我views.py:
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
# Create your views here.
from .serializer import QuestionSerializer
class QuestionView(APIView):
def post(self,request):
serealizer = QuestionSerializer(data=request.data)
if serealizer.is_valid():
serealizer.save()
return Response("Created")
else:
return Response(serealizer.errors)
在我已经包括了我的settings.py文件的末尾以下代码:
MEDIA_ROOT = os.path.join(BASE_DIR,'..','uploaded_media')
MEDIA_URL = '/media/'
我想我在我的意见中犯了一些错误,因为当我试图用django管理面板上传图像。图片上传是成功的。但是,如果我尝试上传使用邮递员我的图片上传不成功。我看到数据库填充了默认的空白值,并且图像在MEDIA_ROOT文件夹中不可用。在邮递员我没有得到任何错误。以下是我的邮递员请求设置的屏幕截图。
下面是从邮递员
POST /questions/ HTTP/1.1
Host: localhost:8000
Cache-Control: no-cache
Postman-Token: 104b89a5-b4c0-4128-c26c-27ac43c59b91
Content-Type: multipart/form-data; boundary=----
WebKitFormBoundary7MA4YWxkTrZu0gW
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="header"
jhkjhkjhkjh
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="details"
this time
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="user_id"
[email protected]
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="image1"; filename=""
Content-Type:
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="image2"; filename=""
Content-Type:
------WebKitFormBoundary7MA4YWxkTrZu0gW--
我在Django和REST API开发新生成的请求代码。我很困惑,如果我在我的views.py或邮递员的请求设置中犯了错误。
我有一个猜测。我想我需要从请求变量手动抓取图像并以某种方式保存它们。但我不知道我的猜测是否正确以及如何去做。
我使用django = 1.10和Python = 3.6。
谢谢男人..这是一个愚蠢的错误..我拉我的头发......:P – Ahnaf