我有一个通过AJAX提交的表单并上传文件。但是,虽然文件已正确上传,但javascript在上传后会显示INTERNAL SERVER ERROR
。我知道该文件已添加到数据库并上传到服务器;除了此错误消息之外,一切似乎都按预期工作。 Django日志中似乎没有错误消息。
我也没有编写处理javascript的代码,所以实际上可能有一种更好的方法可以做到这一点或者我忽视的一些明显的东西。
似乎错误发生在这一行:
response = JSONResponse(data, {}, response_mimetype(self.request))
在我的views.py中:
def response_mimetype(request):
if "application/json" in request.META['HTTP_ACCEPT']:
return "application/json"
else:
return "text/plain"
class UploadedFileCreateView(CreateView):
model = UploadedFile
form_class = UploadedFileForm
def form_valid(self, form):
self.object = form.save(commit=False)
self.object.project_id = self.kwargs['proj_key']
self.object.save()
f = self.request.FILES.get('file')
data = [{
'name': self.object.name(),
'url': "/uploads/xmlfiles/" + self.object.name().replace(" ", "_"),
'delete_url': reverse('fileupload:upload-delete',
kwargs={'pk':self.object.id,
'proj_key':self.kwargs['proj_key']}),
'delete_type': "DELETE"}]
# the problem line
response = JSONResponse(data, {}, response_mimetype(self.request))
response['Content-Disposition'] = 'inline; filename=files.json'
return super(UploadedFileCreateView, self).form_valid(form)
def get_context_data(self, **kwargs):
context = super(UploadedFileCreateView, self).get_context_data(**kwargs)
context['files'] = UploadedFile.objects.all()
context['proj'] = int(self.kwargs["proj_key"])
return context
class JSONResponse(HttpResponse):
"""JSON response class."""
def __init__(self,obj='',json_opts={},mimetype="application/json",*args,**kwargs):
content = simplejson.dumps(obj,**json_opts)
super(JSONResponse,self).__init__(content,mimetype,*args,**kwargs)
我认为问题可能是reverse
方法,但一切都运行正常。以防万一,这是来自urls.py的行:
(r'^projects/(?P<proj_key>\d+)/d/(?P<pk>\d+)$', UploadedFileDeleteView.as_view(), {}, 'upload-delete'),
相关模型:
class UploadedFile(models.Model):
"""This represents a file that has been uploaded to the server."""
STATE_UPLOADED = 0
STATE_ANNOTATED = 1
STATE_PROCESSING = 2
STATE_PROCESSED = 4
STATES = (
(STATE_UPLOADED, "Uploaded"),
(STATE_ANNOTATED, "Annotated"),
(STATE_PROCESSING, "Processing"),
(STATE_PROCESSED, "Processed"),
)
status = models.SmallIntegerField(choices=STATES,
default=0, blank=True, null=True)
file = models.FileField(upload_to=settings.XML_ROOT)
project = models.ForeignKey(Project)
def __unicode__(self):
return self.file.name
def name(self):
return os.path.basename(self.file.name)
def save(self, *args, **kwargs):
if not self.status:
self.status = self.STATE_UPLOADED
super(UploadedFile, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
os.remove(self.file.path)
self.file.delete(False)
super(UploadedFile, self).delete(*args, **kwargs)
编辑:刚在控制台中注意到这个500错误,但我不确定在哪里可以找到堆栈跟踪(因为我没有看到错误模板):
[29/Oct/2013 23:38:56] "POST /upload/projects/1/ HTTP/1.1" 500 11939
答案 0 :(得分:0)
您需要在JSONResponse
类之前移动UploadedFileCreateView
类的定义;在你尚未定义它之前调用该类时,错误发生在那里。
对象被保存,因为您在调用JSONReponse
类之前已经保存了它:
def form_valid(self, form):
self.object = form.save(commit=False)
self.object.project_id = self.kwargs['proj_key']
self.object.save() # object gets saved successfully here
f = self.request.FILES.get('file')
# ...
# Here, JSONResponse is not defined yet, so this is resulting in a 500
# since you have debug=False, its resulting in the default 500 error template
# from your server.
response = JSONResponse(data, {}, response_mimetype(self.request))