我正在处理图片上传表单。当用户上传图片时。在预览区域中使用 ajax 显示该图像...表单重新加载,但似乎不想显示新头像。我得到一个CSRF verification failed. Request aborted
错误。
Reason given for failure: CSRF is missing or incorrect.
我在表单中有一个 csrf_token。
模板:
<form class="nice inline-form" enctype="multipart/form-data" method="POST" action="/profile/edit/" id="avatarLoadForm">
<input type="hidden" name="next" value="/account/settings/">
{% csrf_token %}
<div>
<label for="avatar">Avatar</label>
<div id="preview" class="frame">
<img src="{% if profile.user %}{% thumbnail profile.avatar 120x120 crop %}{% else %}{{ DEFAULT_AVATAR }}{% endif %}" alt="" alt="sample-pic" id="thumb" />
</div>
<input type="file" size="20" id="imageUpload">
and other form info...
</form>
阿贾克斯/jQuery:
$(document).ready(function(){
var thumb = $('img#thumb');
new AjaxUpload('imageUpload', {
action: $('#avatarLoadForm').attr('action'),
name: 'avatar',
csrfmiddlewaretoken: $( "#csrfmiddlewaretoken" ).val(),
onSubmit: function(file, extension) {
$('#preview').addClass('loading');
},
onComplete: function(file, response) {
thumb.load(function(){
$('#preview').removeClass('loading');
thumb.unbind();
});
thumb.attr('src', response);
}
});
也许我的Views.py中缺少一些东西?
@login_required
def edit_profile(request):
context = base_context(request)
if request.method == 'POST':
notify = "You have successfully updated your profile."
user_info_form = UserInfoForm(request.POST, request.FILES)
if user_info_form.is_valid():
if request.is_ajax():
response = simplejson.dumps({"status": "Upload Success"})
return HttpResponse (response, mimetype='application/json')
messages.success(request, 'You have successfully updated your profile.')
user_info_form.save(request.user, profile_type)
return HttpResponseRedirect(request.POST.get('next', '/profile/' + request.user.username + '/'))
else:
initial = {}
initial['first_name'] = request.user.first_name
initial['last_name'] = request.user.last_name
initial['email'] = request.user.email
initial['about'] = profile.about
initial['country'] = profile.country
initial['about'] = profile.about
user_info_form = UserInfoForm(initial=initial)
context['user_info_form'] = user_info_form
context['profile'] = profile
return render_to_response('settings/profile.html', context, context_instance=RequestContext(request))
设置.py:
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.csrf.CsrfResponseMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'pagination.middleware.PaginationMiddleware',
)
文件上传工作没有 ajax 废话。也就是说,它实际上保存了图像,只是没有在预览中显示它。我真的不知道出了什么问题,也不知道为什么会这样。有很多关于 csrf 失败的帖子。但我找不到适合这种情况的。任何见解将不胜感激。