【发布时间】:2014-08-03 18:59:14
【问题描述】:
我很难找到一种使用 django 和tastepie 进行多部分/格式编码图像上传的方法。我在 stackoverflow 上浏览了所有可能的答案,但似乎找不到可行的解决方案。另外,我是python的初学者,所以似乎无法理解很多东西。我已经编写了一些代码,并希望有人指出我做错了什么。
模型.py
import random
from django.db import models
from django.template.loader import get_template
from django.template import Context
import suuq.settings
from usermanagement import utils
from django.contrib.auth.models import UserManager
from django.db.models import ImageField
class adManager(models.Manager):
def create_ad(self, category, title, email, tag, location, address, description, phone, img):
if not category:
raise ValueError('add must have a category')
if not title:
raise ValueError('add must have a title')
if not email:
raise ValueError('ad must have a email')
if not tag:
raise ValueError('ad must have a tag')
if not location:
raise ValueError('ad must have a location')
if not address:
raise ValueError('ad must have a address')
if not description:
raise ValueError('ad must have a description')
if not phone:
raise ValueError('ad must have a phone number')
if not img:
raise ValueError('ad must have a image')
ad = self.create(category = category, title = title, email = UserManager.normalize_email(email).strip().lower(),
tag = tag, location = location, address = address, description = description, phone = phone, img=img)
ad.save()
return ad
class Ad(models.Model):
objects = adManager()
category = models.CharField(max_length=100)
title = models.CharField(max_length=200)
email = models.EmailField(
max_length=255,
unique=True,
)
tag = models.CharField(max_length=200)
location = models.CharField(max_length=50)
address = models.CharField(max_length=200)
description = models.CharField(max_length=140)
phone = models.CharField(max_length=10, null=True)
img = models.ImageField(upload_to="img", null=True, blank=True)
api.py
import json
from django.conf.urls import url
from django import forms
from tastypie.authentication import SessionAuthentication
from tastypie.authorization import Authorization
from tastypie.exceptions import Unauthorized
from tastypie.resources import ModelResource
from tastypie.throttle import CacheThrottle
from tastypie.utils import trailing_slash
from tastypie.validation import FormValidation
from django.db.models import FileField
from tastypie import http, fields
from PIL import Image
from ad.models import Ad
class MultipartResource(object):
def deserialize(self, request, data, format=None):
if not format:
format = request.META.get('CONTENT_TYPE', 'application/json')
if format == 'application/x-www-form-urlencoded':
return request.POST
if format.startswith('multipart'):
data = request.POST.copy()
data.update(request.FILES)
return data
return super(MultipartResource, self).deserialize(request, data, format)
class AdResource(ModelResource, MultipartResource):
img = fields.FileField(attribute="img", null=True, blank=True)
class Meta:
queryset = Ad.objects.all()
resource_name = 'ad'
fields = ['id', 'category', 'title','email','tag','location', 'address', 'description', 'phone', 'img']
allowed_methods = ['post','get','delete']
include_resource_uri = False
def prepend_urls(self):
return [
url(r"^(?P<resource_name>%s)/add%s$" %
(self._meta.resource_name, trailing_slash()),
self.wrap_view('add_ad'), name="add_ad"),
]
def add_ad(self, request, **kwargs):
self.method_check(request, allowed=['post'])
data = json.loads(request.body)
category = data.get('category', '')
title = data.get('title', '')
email = data.get('email', '')
tag = data.get('tag', '')
location = data.get('location', '')
address = data.get('address', '')
description = data.get('description', '')
phone = data.get('phone', '')
if(request.method == 'POST'):
if "multipart/form-data" not in str(request.META['CONTENT_TYPE']):
return
else:
if('img' in request.FILES):
upload = request.FILES['img']
img = Image.open(upload)
return
else:
return
else:
return
ad = Ad.objects.create_ad(category=category, title=title, email=email, tag=tag,
location=location, address=address, description=description, phone=phone, img=img)
return self.create_response(request, {
'success': True,
'ad_id': ad.id,
'message': 'ad address successfully added'
})
我知道我的代码没有正确缩进,但我在开发端正确缩进了它。请帮我解决我的逻辑,我真的卡住了。
【问题讨论】:
标签: django python-2.7 file-upload tastypie multipartform-data