我是Ionic,AngularJS和django-restframework的新手,所以在构建我的第一个应用程序的过程中,我遇到了下面突出显示的这些问题。
app.js
angular.module('starter', ['ionic', 'starter.controllers', 'starter.services', 'ngCordova'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
if(window.cordova && window.cordova.plugins.Keyboard) {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form i
nputs)
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
// Don't remove this line unless you know what you are doing. It stops the viewport
// from snapping when text inputs are focused. Ionic handles this internally for
// a much nicer keyboard experience.
cordova.plugins.Keyboard.disableScroll(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
});
})
.config(function($stateProvider, $urlRouterProvider,$compileProvider, $httpProvider) {
$httpProvider.defaults.withCredentials = true;
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
$stateProvider
// setup an abstract state for the tabs directive
.state('app', {
abstract:true,
url: '/app',
templateUrl: 'templates/app.html'
})
.state('app.welcome', {
url: '/welcome',
views: {
'welcome': {
templateUrl: 'templates/welcome.html',
}
}
})
.state('app.news', {
url: '/news',
views: {
'welcome': {
templateUrl: 'templates/news.html',
controller: 'homeCtrl'
}
}
})
.state('app.vendor', {
url: '/vendor',
views: {
'welcome': {
templateUrl: 'templates/vendor.html',
controller: 'homeCtrl'
}
}
})
.state('app.map', {
url: '/map',
cache:false,
views: {
'welcome': {
templateUrl: 'templates/map.html',
controller: 'mapCtrl'
}
}
})
.state('app.report', {
url: '/report',
views: {
'welcome': {
templateUrl: 'templates/report.html',
controller: 'ReportCtrl'
}
}
});
$urlRouterProvider.otherwise('app/welcome');
});
controller.js
$scope.imagereport = {
imagelist:[],
addimage :function(){
var nt = $scope.imagereport;
$ionicActionSheet.show({
buttons: [
{ text: 'From Camera' },
{text:'From Gallery'}
],
titleText: 'Supporting Pictures',
cancelText: 'Close',
buttonClicked: function(index) {
if(index === 0) {
$scope.addimages(1);
}
else{
$scope.addimages(2);
}
}
});
}
};
$scope.addimages =function(eve) {
$scope.imgo;
var options = {
quality : 75,
destinationType: 1,
targetWidth: 200,
targetHeight: 200,
sourceType:eve,
correctOrientation:true,
saveToPhotoAlbum: false,
encodingType: 0 // 0=JPG 1=PNG
};
Camera.getPicture(options).then(function(imageData) {
var obj = imageData;
$scope.imagetaken.push(obj);
$scope.imgo =imageData;
var opt = {
fileKey : "file",
fileName :fileURL.substr(imageData.lastIndexOf('/') + 1),
chunkedMode :false,
mimeType : "image/jpeg",
headers :{ Connection:"close", 'CONTENT-TYPE':'application/json', Vary:'Accept' ,'Access-Control-Allow-Headers': 'x-requested-with' },
//popoverOptions: CameraPopoverOptions,
saveToPhotoAlbum: false
};
var url = "http://riwama.sites.djangoeurope.com/addtemprorarypicapi"
$cordovaFileTransfer.upload( encodeURI("http://riwama.sites.djangoeurope.com/addtemprorarypicapi"),imageData, opt).then(
function(result){
console.log('Success: ' +JSON.stringify(result));
$.each(result,function(){
$.each(this,function(k,v){
var did = k;
$scope.ids.push(did);
});
});
var im = $scope.imagetaken;
$scope.imagetaken.push(imageData);
},
function(err){
alert('can not upload image because: ' +JSON.stringify(err));
console.log(err)
},
function (progress) {
$timeout(function () {
$scope.upProgress = (progress.loaded / progress.total) * 100;
});
});
}, function(err) {
console.log(err);
});
Django RestFramework序列化程序
from rest_framework import serializers as ser
from .models import temprorary_report_pic
class temprorary_ser(ser.ModelSerializer):
class Meta:
model = temprorary_report_pic
read_only_fields = ('Picture',)
与序列化程序绑定的模型:
class temprorary_report_pic(models.Model):
Picture = models.ImageField(upload_to = 'Temprorary_report_pic/%Y/%m/%d',blank = True, null = True)
def __unicode__(self): # __unicode__ on Python 2
return '%s' %self.id
实现Django rest视图的Modelviewset
的视图from .models import *
from rest_framework import permissions
from rest_framework.viewsets import ModelViewSet
from rest_framework.decorators import detail_route,parser_classes
from rest_framework.parsers import MultiPartParser, FormParser,FileUploadParser
from rest_framework import mixins
from rest_framework.permissions import AllowAny
from rest_framework import generics
from .drf_serializers import temprorary_ser
restapi_permission_classes = (AllowAny,)
class addtemprorarypicapi(ModelViewSet):
queryset = temprorary_report_pic.objects.all()
serializer_class = temprorary_ser
#permission_classes = (AllowAny,)
parser_classes = (MultiPartParser,FormParser,FileUploadParser,)
def perform_create(self, serializer):
serializer.save(Picture=self.request.data.get('file'))
我在django上安装了CORS,设置如下:
CORS_URLS_REGEX = '^.*$'
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_HEADERS = (
'x-requested-with',
'content-type',
'accept',
'origin',
'authorization',
'accept-encoding',
'x-csrftoken'
)
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_METHODS = ( 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS' )
CORS_ALLOW_CREDENTIALS = True
重定向请求的url.py:
router = DefaultRouter()
router.register(r'^addtemprorarypicapi', addtemprorarypicapi)
urlpatterns = [
url(r'^', include(router.urls)),
]