我正在使用Django 2.0.1
基本上我正在尝试实现cropperjs并且首先我遇到了403的问题,这使我无法上传图像(这是因为脚本返回Json响应而我没有查看处理它)所以我做了,但后来我遇到了这个问题。请帮助我不配,我付税。
在我的forms.py
上class EmployeeForm(forms.ModelForm):
class Meta:
model = Employee
fields = '__all__'
exclude = ['user', 'date_joined','Credits_earned','skills']
department = forms.CharField(
widget=forms.TextInput(attrs={
"class": "form-control",
"placeholder": _("User...")
}
)
)
title = forms.CharField(
widget=forms.TextInput(attrs={
"class": "form-control",
"placeholder": _("Title...")
}
)
)
avatar = forms.ImageField(
widget=forms.FileInput()
)
在我的views.py
上from django.http import JsonResponse
class EmployeeUpdate(JsonResponse,UpdateView):
template_name = 'test.html'
model = Employee
form_class = EmployeeForm
success_url = '/'
def get_queryset(self):
return super(EmployeeUpdate, self).get_queryset().filter(user=self.kwargs['pk'])
def render_to_response(self, context, **response_kwargs):
return self.render_to_json_response(context, **response_kwargs)
模板上的脚本:
<script>
window.addEventListener('DOMContentLoaded', function () {
var avatar = document.getElementById('avatar'); // Current avatar
var image = document.getElementById('image');
var input = document.getElementById('id_avatar'); // Image input
var $progress = $('.progress');
var $progressBar = $('.progress-bar');
var $alert = $('.alert');
var $modal = $('#modal');
var cropper;
$('[data-toggle="tooltip"]').tooltip();
input.addEventListener('change', function (e) {
var files = e.target.files;
var done = function (url) {
input.value = '';
image.src = url;
$alert.hide();
$modal.modal('show');
};
var reader;
var file;
var url;
if (files && files.length > 0) {
file = files[0];
if (URL) {
done(URL.createObjectURL(file));
} else if (FileReader) {
reader = new FileReader();
reader.onload = function (e) {
done(reader.result);
};
reader.readAsDataURL(file);
}
}
});
$modal.on('shown.bs.modal', function () {
cropper = new Cropper(image, {
aspectRatio: 1,
viewMode: 3,
});
}).on('hidden.bs.modal', function () {
cropper.destroy();
cropper = null;
});
document.getElementById('crop').addEventListener('click', function () {
var initialAvatarURL;
var canvas;
$modal.modal('hide');
if (cropper) {
canvas = cropper.getCroppedCanvas({
width: 160,
height: 160,
});
initialAvatarURL = avatar.src;
avatar.src = canvas.toDataURL();
$progress.show();
$alert.removeClass('alert-success alert-warning');
canvas.toBlob(function (blob) {
var formData = new FormData();
formData.append('avatar', blob);
$.ajax('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
data: formData,
processData: false,
contentType: false,
xhr: function () {
var xhr = new XMLHttpRequest();
xhr.upload.onprogress = function (e) {
var percent = '0';
var percentage = '0%';
if (e.lengthComputable) {
percent = Math.round((e.loaded / e.total) * 100);
percentage = percent + '%';
$progressBar.width(percentage).attr('aria-valuenow', percent).text(percentage);
}
};
return xhr;
},
success: function () {
$alert.show().addClass('alert-success').text('Upload success');
},
error: function () {
avatar.src = initialAvatarURL;
$alert.show().addClass('alert-warning').text('Upload error');
},
complete: function () {
$progress.hide();
},
});
});
}
});
});
</script>
修改 这是完整的追溯:
Request Method: GET
Request URL: http://127.0.0.1:8000/test2/1
Django Version: 2.0.1
Python Version: 3.6.1
Installed Applications:
['accounts.apps.AccountsConfig',
'dashboard.apps.DashboardConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback (most recent call last):
File "C:\Users\Loki\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\exception.py", line 35, in inner
response = get_response(request)
File "C:\Users\Loki\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py", line 128, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\Loki\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Loki\AppData\Local\Programs\Python\Python36\lib\site-packages\django\views\generic\base.py", line 63, in view
self = cls(**initkwargs)
TypeError: __init__() missing 1 required positional argument: 'data'
答案 0 :(得分:0)
嗯,最终工作的是这个剪辑:
# encoding: utf-8
from django.http import HttpResponse
import json
MIMEANY = '*/*'
MIMEJSON = 'application/json'
MIMETEXT = 'text/plain'
def response_mimetype(request):
"""response_mimetype -- Return a proper response mimetype, accordingly to
what the client accepts, as available in the `HTTP_ACCEPT` header.
request -- a HttpRequest instance.
"""
can_json = MIMEJSON in request.META['HTTP_ACCEPT']
can_json |= MIMEANY in request.META['HTTP_ACCEPT']
return MIMEJSON if can_json else MIMETEXT
class JSONResponse(HttpResponse):
"""JSONResponse -- Extends HTTPResponse to handle JSON format response.
This response can be used in any view that should return a json stream of
data.
Usage:
def a_iew(request):
content = {'key': 'value'}
return JSONResponse(content, mimetype=response_mimetype(request))
"""
def __init__(self, obj='', json_opts=None, mimetype=MIMEJSON, *args, **kwargs):
json_opts = json_opts if isinstance(json_opts, dict) else {}
content = json.dumps(obj, **json_opts)
super(JSONResponse, self).__init__(content, mimetype, *args, **kwargs)
然后在我看来:
class EmployeeUpdate(UpdateView):
template_name = 'test.html'
model = Employee
form_class = EmployeeForm
success_url = '/'
def get_queryset(self):
return super(EmployeeUpdate, self).get_queryset().filter(user=self.kwargs['pk'])
def form_valid(self, form):
self.object = form.save()
data = {'data': 'formData'}
response = JSONResponse(data, mimetype=response_mimetype(self.request))
return response
我仍然需要在我的模板中修复一些内容,以便输入到达应有的位置。虽然感谢肝脏。